With the guideline support library and utilities like gsl_Expects C++ implements contracts for the time being (there are plans to bake this stuff into the language in the future). Using this feature and depending on your project setup, contract violation will likely:
- throw an exception or
- call terminate
I was wondering what the recovery strategy should be. Obviously in the second case (where you set up contract violations to call terminate) there's none, but even in the first case it's hard to recover; since the exception is of some inner type (e.g. fail_fast which derives from logic_error) it's hard to structure a recovery strategy: what exception(s) should I catch, at which level, is there useful information that will help me recover (I think file+line is meant for a human reader to do a post mortem analysis).
So given all that, my question is: Are you meant to recover from contract violations? If yes how? Is there a source describing how to do it? If not, is it a good idea to separate my error checking+handling from contract checking and only think about contracts in terms of hard errors?
I guess the second choice is what I'm leaning towards but the annoying thing is that these violations will cause my whole program to crash instead of nulling out a single function.
I could structure contract bearing functions like this:
std::optional<return_t> my_function(Arg arg)
{
std::optional<return_t> ret;
try {
gsl_Expects(...); // do contract checking
/* rest of function */
} catch (fail_fast& e) {
// report contract violation
}
return ret; // Exceptions from contract violations are turned into empty optional
// Other exceptions are handled like before (locally or from the caller)
}
but it feels like it beats the purpose of using contracts.