Say I have nested methods a, b, c, d, e on each level we return errors in the normal course of operations, but e could also throw an exception (e.g. out of memory on STL insert). The exceptions are very seldom and how fast/slow actual unwinding is happening is not an issue.
What is the most appropriate strategy for exception handling in this case?
- Put it into the lowest level and convert to a normal error condition.
Pros: do not need to write exception safe code, simplest to implement, easiest to test, easiest to understand, minimum compile time information required for unwinding.
Cons: does not look cool, adds noticeable try/catch clatter - practically around every insert and push_back, up to the extent of writing exception safe wrappers around STL containers, there are opinions that there is run time performance penalty for try blocks (and there are opinions that there is no penalty at all).
- Handle it it at the top.
Pros: looks cool, no clatter.
Cons: really hard to visually verify that all code in between is indeed exception safe to testing all exception unwinding paths will be
- Handle it the very top as a complete restart of the application: zap everything that was not zapped by exception handling and start again
Pros: predictable, will tolerate minor blemishes in exception safe code, way better than crash.
Cons: way too harsh
- Writing custom allocator, allowing to check memory reserve at a() before diving down the call stack.
void a()
{
...
x = b();
...
}
int b()
{
y = c();
...
return y + d();
}
int d()
{
...
z = e();
...
}