可能是重复问题:
Java中的try块是否应该尽可能紧密地作用于范围内?
保持try块小有没有性能优势(特别是在C++或Java中),除了更明确地告诉读者哪个语句可能会抛出异常之外。
给定以下方法,我不希望从该方法中抛出异常。
void function() throws Exception
{
statement1
statement2
statement3 // can throw
statement4
statement5
}
你认为这样做更好吗:
选项1
void function()
{
try {
statement1
statement2
statement3 // can throw
statement4
statement5
}
catch (...) {
}
}
或者
选项2
void function()
{
statement1
statement2
boolean success = false;
try {
statement3 // can throw
success = true;
}
catch (...) {
}
if (success)
{
statement4
statement5
}
}