有一个 X 类。
X 类中的方法 method()
抛出 SomeException
。
我想知道哪种处理异常的方法更好——更高效。如果它围绕 try-block 方法抛出异常和所有依赖项,或者将依赖项保留在 try-block 之外,但在失败后从方法返回。
1.
public void test() {
X x = new X();
try {
T temp = tx.method();
temp.doWhatever();
}
catch(SomeException e) { handleException(e); }
}
或
2.
public void test() {
X x = new X();
T temp = null;
try {
temp = tx.method();
}
catch(SomeException e) {
handleException(e);
return;
}
temp.doWhatever();
}
<小时/>
编辑:(在注释之后)
更重要的是,我这样理解我的代码:
1.
tx.method()
将抛出异常,因此接下来要执行的是 catch
- block 。 temp
仍然是 null
并不重要,因为程序会跳过 temp.doWhatever();
行,并且不会出现 NullPointerException
。
2.
这里我使用 return
指令,因为我不想执行 temp.doWhatever()
因为 temp
是 null
最佳答案
异常工作方式的关键点之一是您可以使用样式编号 1:让代码块放心地执行,无论它在哪里中断,流程都会被中断并处理错误。所以我总是建议第一种风格。
关于java - 正确高效的编程风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11457257/