C/C++ Library, mos@ua 1.0
cpplib-mos
DbC-DEM

The following macros are an approximation to implement a Disciplined Exception Mechanism using only the language preprocessor. More...

Macros

#define rescue_retry
 To place at the beginning of the code to be retried.
 
#define rescue_begin
 To place at the beginning of the rescue code.
 
#define rescue_end
 To place at the end of the rescue code.
 
#define retry
 Jump to the beginning of the code to be retried (must be inside the rescue code!).
 

Detailed Description

The following macros are an approximation to implement a Disciplined Exception Mechanism using only the language preprocessor.

Unlike the usual try/catch exception mechanism to handle errors, a Disciplined Exception Mechanism (DbC-DEP) follows a much simpler approach: It implements the idea that, in a DbC approach, a function (or method) can only succeed, by fully observing its contract, or fail; no other behavior is acceptable. Thus, a function only returns if it succeeds (observing its contract). In the presence of a failure, it launches an exception. Recovering from a failure is only possible if a function can fulfill its contract in a new attempt (using a different algorithm, or any other convenint way).

This perspective simplifies tremendously error handling solving two very serious problems with common try-catch exception mechanisms:

However, in the DbC-DEP a failed function causes the failure of the client function, and so on, until, if required, a rescue is attempted. A rescue never compromises the function/module contract, as it allows only a retry to fulfill the contract (probably by using a different approach, or in a function which prescribes a weaker contract for an alternative acceptable behavior).

Example:

#include <dbc.h>
...
void redundant_function_with_two_alternative_implementations(...)
{
require (..., "..."); // precondition
int algorithm = 1;
switch(algorithm)
{
case 1:
...
break;
case 2:
...
break;
}
ensure (..., "..."); // postcondition
algorithm++;
if (algorithm <= 2)
}
Design-by-Contract module.
#define rescue_end
To place at the end of the rescue code.
Definition dbc.h:398
#define retry
Jump to the beginning of the code to be retried (must be inside the rescue code!).
Definition dbc.h:404
#define rescue_begin
To place at the beginning of the rescue code.
Definition dbc.h:391
#define rescue_retry
To place at the beginning of the code to be retried.
Definition dbc.h:384
#define require(condition, message)
Checks the verification of a precondition.
Definition dbc.h:163
#define ensure(condition, message)
Checks the verification of a postcondition.
Definition dbc.h:199

Since exceptions are necessary here, these macros are only applicable in C++ (with EXCEPTION_POLICY macro defined), not in C (for a C approach see c-dbc library).

By default, rescue clause only catches DbC errors (DbC_Error*). This behavior can be modified to catch all types of exceptions be defining the compiling macro CATCH_ALL.