105

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.

Steve
  • 5,802
  • 12
  • 54
  • 76
  • 11
    Do you want the processing to stop as soon as the first error occurs ( the first example ) or it can continue even if a part of the processing fail (the other one)? – David Pratte Jul 13 '10 at 17:53
  • 3
    @DLP - I'd like it to stop processing - I see someone mentioned it after you. That's a good point. – Steve Jul 13 '10 at 17:59
  • 5
    Although you tagged this with C# and .net, I think it is really language agnostic. This question applies to any language with exceptions such as Java, C++, JavaScript, OCaml, F#, Python, Clojure, etc. It would also apply to the condition/restart system in Common Lisp and various other Lisps. So I'd ask for you to make this language agnostic...Your call though. – A. Levy Jul 13 '10 at 18:09

11 Answers11

125

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
}
jcjr
  • 1,503
  • 24
  • 40
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • 7
    +1 , Highlighted in the first example, ensure that the General exception Handler is last in the declaration so that you handle specific first then anything else outside your control is handled in a generic fashion. – leeroya Nov 26 '15 at 10:53
  • As stated here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch, The use of conditional catches is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. – JLavoie Nov 01 '17 at 18:56
22

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 6
    +1: I agree completely, though I'd probably write this as "If I could choose the second, I would..", since I think this is the right thing to do any time it's possible... – Reed Copsey Jul 13 '10 at 17:52
11

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

Ed S.
  • 122,712
  • 22
  • 185
  • 265
11

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.

zwol
  • 135,547
  • 38
  • 252
  • 361
5

Second method is better in my opinion because it allows you to trap errors with more accuracy.

Also wrapping your entire code inside one big try/catch block is bad, if your app has some sort of problem and it crashes but since you trapped a big generic execption the chance that you can actualy handle it correctly is lower. You should have spesfic parts inside try catch, like if your reading a file or taking user input. That way you can better handle that exeception

EKS
  • 5,543
  • 6
  • 44
  • 60
3

There are time we want to show specific error to user.

try{
   try{
      ... send message
   }
   catch(exception e){
    ...log error
    ...rethrow  send related error/show custom error
   }
   try{
       ...try to receive response
   }
   catch(exception e){
       ...show receive related error
   }
   //finally close the connection
   }finally{
        ...close connection
   }
Jennis Vaishnav
  • 331
  • 7
  • 29
Ashburn RK
  • 450
  • 3
  • 8
2

I prefer the second method - it makes debugging easier, error handling more accurate and also feeds nicely into your unit testing nicely too.

Andy
  • 2,764
  • 6
  • 24
  • 33
2

I would go for the 2nd option, but whenever I see this code pattern my first feeling is to think about splitting it into multiple functions/methods. Obviously whether to do so depends on what the code is doing ;)

barrylloyd
  • 1,599
  • 1
  • 11
  • 18
2

It depends on the nature of the type of errors happen in your code.

  1. If the handling of those errors you are going to do is same go for single try ... catch for that group of code. Else it will be too tedious.

  2. If the errors required different handling, separate it because you have to.

DO NOT APPLY A SINGLE METHOD FOR ALL CASES. PROGRAMMING MOST OF THE TIME IS CONTEXT SPECIFIC :)

You need to reach a balance of "GOOD/COMPLEX" and "BAD/SIMPLE". The more you code, you will be less stuck in this kind of dilemma :)

Happy programming!

ttchong
  • 307
  • 2
  • 9
1

Second method. Keeping the code that might throw an exception separate from other code - keeps the section smaller and easier to manage instead of wrapping all code, even that which will not throw exceptions.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
-1

2nd way but ideally use code guards - try/catch can be costly, if you catch an exception.

Phil C
  • 3,687
  • 4
  • 29
  • 51
  • 2
    Try/catch in C# is really not very costly, unless you actually catch something... – Reed Copsey Jul 13 '10 at 17:53
  • 3
    PS: I realize this answer is 7yrs old but want to put it in context of 2017.... The performance hit of Try/Catch is greatly over quoted and imaginery performance gains are NEVER a good reason to better, more reliable code, especially when you realize when .NET came out the best computer you could buy was a Pentium 4 w/ 1-2GB ram and today we have 4 cores, hyper threaded, that's more than 8x the speed, and 8-16GB RAM is the norm. On top of that .NET compiled code is also faster than it was 15yrs ago even on the same hardware. Calling Try/Catch slow is a myth and it needs to stop. – TravisO Jan 25 '17 at 13:15