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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With