Can I have nested try-catch blocks? For example:
void f()
{
try
{
//Some code
try
{
//Some code
}
catch(ExceptionA a)
{
//Some specific exception handling
}
//Some code
}
catch(...)
{
//Some exception handling
}
}//f
-
Yes, you can.
-
Yes perfectly legal.
Though it would be best to move inner ones into another method so it looks cleaner and your method(s) are smaller
-
As already stated, it is possible, but you have to see the 'fall-through'-scheme in this. If in the first try-catch-block your exception is caught, it will not get caught by the outer catch-block. However if it does not get caught by the inner catch-block, it will try to find a matching exception-handler in the outer catch-block.
You can also explicitely raise the exception further to the next exception-handler by using
throw;in your inner exception-handler.For example this code:
try { try { throw std::runtime_error("Test"); } 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; }Will result in:
Inner Exception-Handler: Test Outer Exception-Handler: Test
This works because std::runtime_error is derived from std::exception. You should also note that in such a trivial example it is also possible to just write the catch-blocks after each other, but if you want to execute other code after the first catch-block you will have to nest them.
-
Its legal but its not all that useful unless you are throwing an exception from your inner catch(). For example, you might want to catch a system level exception but throw your own exception object for code clarity.
MSalters : It IS useful if the outer catch handles a different set of exceptions -
Yes, that's legal. As ouster said, one way to deal with it is to put the inner try-catch block in its own function and call that function from your outer try-catch block.
Another way to handle it is with multiple catch blocks.
void f() { try { //Some code that throws ExceptionA //Some code that throws ExceptionB } catch(ExceptionA ea) { //Some exception handling } catch(ExceptionB eb) { //Some exception handling } }//fThe thing to be careful of here is the specificity of the exception types in your catch blocks. If ExceptionB extends ExceptionA in the example above, then the ExceptionB block would never get called because any ExceptionB that gets thrown would be handled by the ExceptionA block. You have to order the catch blocks in most specific to least specific order when dealing with Exception class hierarchies.
0 comments:
Post a Comment