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;
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 accounted 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.
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
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.
Wrap your critical parts to keep your message clear and to the point.
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.
I think your first example is better practice than your second.