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:28

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.

查看更多
登录 后发表回答