Multiple try-catch or one?

It depends. If you want to provide special handling for specific errors then use multiple catch blocks:

try
{ 
    // code that throws an exception
    // this line won't execute
}
catch (StackOverflowException ex)
{
    // special handling for StackOverflowException 
}
catch (Exception ex)
{
   // all others
}

If, however, the intent is to handle an exception and continue executing, place the code in separate try-catch blocks:

try
{ 
    // code that throws an exception

}
catch (Exception ex)
{
   // handle
}

try
{ 
    // this code will execute unless the previous catch block 
    // throws an exception (re-throw or new exception) 
}
catch (Exception ex)
{
   // handle
}

You're thinking about this the wrong way. What do you need to do in your catch blocks? If you would recover from any of the possible exceptions by running the same code, no matter which operation threw the exception, then use one catch block. If you need to do different clean-up operations depending on which operation threw, then use multiple catch blocks.

Also, if you can use try/finally or the RAII pattern instead of try/catch, then you should.


If I could choose the second I would probably separate this into two functions.


Neither, just use multiple catch blocks for specific exceptions (unless there is just a ton of code in the block and only a couple of lines may throw an exception.In that case I would go with the second method).