How many statements in a try/catch statement?

2019-02-17 05:00发布

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;

13条回答
劫难
2楼-- · 2019-02-17 05:13

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.

查看更多
等我变得足够好
3楼-- · 2019-02-17 05:17

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

查看更多
女痞
4楼-- · 2019-02-17 05:17

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.

查看更多
Juvenile、少年°
5楼-- · 2019-02-17 05:22

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

查看更多
再贱就再见
6楼-- · 2019-02-17 05:22

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.

查看更多
\"骚年 ilove
7楼-- · 2019-02-17 05:22

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

查看更多
登录 后发表回答