If I have a code like the following:
try {
doSomething();
} catch (...) {
noteError();
}
void noteError() {
try {
throw;
} catch (std::exception &err) {
std::cerr << "Note known error here: " << err.what();
} catch (...) {
std::cerr << "Note unknown error here.";
}
throw;
}
Will the original exceptions get thrown from both places inside the lower frame of noteError()?
Your original code was fine. You caught different exception types and called a function that would log a message and rethrow. The throw
statement is not required to appear directly inside the corresponding catch
block. If you call one of those "note" functions and you're not currently handling an exception, though, then your program will call terminate()
.
Your new code is also fine. It's OK to catch everything and then call another function that rethrows to go to a more specific handler. That's the exception dispatcher idiom described in the C++ FAQ. It looks a little peculiar to rethrow the exception after the dispatching block has finished, but if that same throw
statement had occurred after noteError
returned (inside the original catch
block) instead of where it is now, then it would be perfectly ordinary; it's demonstrated in the standard, §15.1/6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With