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
}
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).