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?
No, there are no downsides. That's the way you should do it.
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!
It's a perfectly valid way to code.
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
try //outer try{}
{
try //inner try{}
{
throw std::runtime_error("Demo");
}
catch (std::runtime_error& e)
{
std::cerr << "Inner Exception-Handler: " << e.what() << std::endl;
throw;
}
}
catch (std::exception& e)
{
std::cerr << "Outer Exception-Handler: " << e.what() << std::endl;
}
return 0;
}