views:

1158

answers:

5

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
A: 

Yes, you can.

Mehrdad Afshari
+11  A: 

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

ouster
+5  A: 
Patrick Daryll Glandien
A: 

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.

It IS useful if the outer catch handles a different set of exceptions
MSalters
+2  A: 

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
    }
}//f

The 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.

Bill the Lizard