Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple try-catch or one?

Normally, I'd do this:

try {     code      code that might throw an anticipated exception you want to handle      code      code that might throw an anticipated exception you want to handle      code } catch  {  } 

Are there any benefits to doing it this way?

code  try {     code that might throw an anticipated exception you want to handle } catch { }  code  try {     code that might throw an anticipated exception you want to handle } catch { }  code 

Update:

I originally asked this question w/reference to C#, but as A. Levy commented, it could apply to any exception handling language, so I made the tags reflect that.

like image 293
Steve Avatar asked Jul 13 '10 17:07

Steve


2 Answers

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 } 
like image 68
Jamie Ide Avatar answered Oct 09 '22 09:10

Jamie Ide


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

like image 30
Darin Dimitrov Avatar answered Oct 09 '22 07:10

Darin Dimitrov