The code I want to execute in my exception handler may itself throw an exception.
Is the follow structure legal C++? If yes, are there any downsides?
try
{
// ...
}
catch (const E&)
{
try
{
// ...
}
catch (const F&)
{
}
}
If the exception thrown from func2() in the inner try block is type_err , the program skips out of both try blocks to the second catch block without invoking func3() , because no appropriate catch block exists following the inner try block. You can also nest a try block within a catch block.
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
How to Avoid the Nesting? Extracting the nested part as a new method will always work for any arbitrarily nested Try-Catch-Finally block. So this is one trick that you can always use to improve the code.
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Actually, there is even an interesting technique for using nested try/catch-blocks: assume you have multiple functions which need effectively the same exception handling. Especially when wrapping another interface this is common scenario. In this case it is possible to catch all exceptions, call a function from the exception handler, and in this function rethrow the exception to implement the actual exception handling:
void fancy_handler() {
try {
throw; // assumes that fancy_handler() is called from catch-clause
} catch (std::runtime_error const& rt) {
std::cout << "runtime-error: " << ex.what() << "\n";
} catch (std::exception const& ex) {
std::cout << "excption: " << ex.what() << "\n";
} catch (...) {
std::cout << "unknown exception\n";
}
}
void foo() { try { do_foo(); } catch (...) { fancy_handler(); } }
void bar() { try { do_bar(); } catch (...) { fancy_handler(); } }
I just love avoiding duplicate [non-trivial] code!
No, there are no downsides. That's the way you should do it.
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