views:

306

answers:

14

Should I put multiple statements in a try and then catch all possible exceptions, or should I put only one statement in the try statement?

Example:

try {
    MaybeThrowIOException();
    MaybeThrowFooBarException();
    return true;
} catch (IOException e) {
    // ...
} catch (FooBarException e) {
   // ... 
}

Or

try {
    MaybeThrowIOException();
} catch (IOException e) {
    // ...
}

try {
    MaybeThrowFooBarException();
} catch (FooBarException e) {
   // ... 
}

return true;
+2  A: 

The more statements you put, the less specific about the cause of exception you can be potentially.

But of course it depends if the function calls/statements carry overlapped exceptions i.e. if all exceptions can be account for in a specific manner, then it is still ok.

In your example, you seem to be having non-overlapped exceptions so your first form is ok.

jldupont
A: 

I think your first example is better practice than your second.

JonoW
+5  A: 

Wrap your critical parts to keep your message clear and to the point.

Jonathan Sampson
I agree, there is no single solution here as it needs to be a case by case. Sometimes your first example will make more sense, and sometimes your second.
cjstehno
+1 for this. Group it based on what you are trying to do. If the first set of statements exist to read a file, group those together (because of one part fails, the rest of it doesn't matter). If the statements are doing two separate things (and the second doesn't rely on the first), then feel free to split them.
JasCav
A: 

In accordance with what jldupont says, I try to always separate my potential risk statements into multiple try/catch blocks. That way when something goes wrong, you know exactly where it was and you can have specific error messages for each problem.

JMTyler
A: 

you can use any of them.

but if using the first then you should catch the more specific exceptions.

GK
A: 

Normally you can separate what you are trying to do into a specific task. Put the code related to that task into one try catch and then if something goes wrong you know that task has failed and you can try to recover from there.

i find this method reduces the amount of catch code you need to write and keeps related logic together.

Kaius
A: 

It depends, but I find code much harder to read if multiple try catch blocks are in a given flow.

GregS
+1  A: 

You can handle multiple types of exceptions through single try / catch loop. But take care of order in which you are going to handle exceptions. Order of catch exception block does matter.

Manoj
A: 

The first choice, it allows more understandable and readable code, more so your procedure or function should be trying to do a very specific action, the fact that you have 2 separate calls that might throw 2 separate exceptions means its doing more than it supposed to, maybe this is necessary

Either spit the 2 calls into 2 separate methods or go with the first approach.

The only reason you might want to go with the second approach is if your method does 2 actions and a little bit more, but you only want to handle 2 lines of code for exceptions, and maybe wrap them and continue executing but this isn't advised

Neil
A: 

I would prefer using multiple statements in a try block and then catch all possible exceptions. Not sure why but I always do that while coding

ria
A: 

If they are truly separate like that, then the first is better practice, simply because it's shorter.

However, if it's possible for MaybeThrowIOException() to throw a FooBarException, or for MaybeThrowFooBarException() to throw a IOException, then you should only wrap them together if you want them both to take the same action upon an exception!

BlueRaja - Danny Pflughoeft
+2  A: 

It depends of the case , but it's important to notice that in the first case MaybeThrowFooBarException() is nerver called if MaybeThrowIOException() throws an exception, and in the second case MaybeThrowFooBarException will be allways called unless a exception is rethrown in the first catch

Telcontar
+1  A: 

I think the best practice is the one detailed in the book The Pragmatic Programmer, exceptions should rarely be used - but when being used it should clear to what it's suppose to be handling.

So, my vote is example #2.

Anders
Where does it says so? All I could find was: "We believe that exceptions should rarely be used as part of a program's normal flow; exceptions should be reserved for unexpected events."
Sjoerd
A: 

If the method you are calling can return FooExeption() and BarException() and you want to catch both, then the first example make the most sense - quite a few API's do this, particularly ones that are higher level (as they themselves are using more things which can raise exceptions).

If you are doing two separate things then it really entirely depends on what you want the outcome to be:

  • If an exception in either ultimately amount to the same thing as far as your code is concerned, and you don't care about having roll anything back (or it's simple to roll back from either and you can easily do it in a single finally block - assuming the language supports this) then there is no point in having two separate try/catch blocks.

  • If the error types are very varied and you care what happens if the first method raises an exception (e.g. and need to do some operations to roll back) and you want to continue executing the second operation, even if the first one threw an exception, then the second approach would be more appropriate.

  • If you care if the first method fails and you don't want to continue executing if it does, then it's worth remembering that you can nest try/catch, though it's best not to go overboard with this. If used well it's much clearer than trying to follow bools in if statements to check if a block should execute or not.

e.g.

try {

    MaybeThrowFooException();

    try {
    // Will only be called as long as MaybeThrowFooException() is not thrown
        MaybeThrowBarException();

    } catch (BarException ex) {

    }

} catch (FooException ex) {

}
Iain Collins