有一个类X. 方法method()
在X类抛出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();
}
编辑:(注解之后)
更重要的是我undersand我的代码这样的:那么这将excetuted接下来的事情就是catch
1. tx.method()
会抛出异常 - 块。它并没有消失,temp
仍然是null
,因为程序跳过temp.doWhatever();
行,并且不会有NullPointerException
。
2. 这里我用return
指令,因为我不想执行temp.doWhatever()
因为temp
是null
选项1对我来说更加清晰 – Eric 2012-07-12 17:32:34
(1)为什么一个'public void test'和另一个'public static void main'? (2)你意识到在第二块代码中,它意味着'temp.doWhat''不会有例外被捕获? – 2012-07-12 17:32:57
@notfed:对于你的问题(2),虽然(我们可以假设没有任何东西被抛出),但OP没有提及任何关于'doWhatever'抛出'Exception'的信息。 – nhahtdh 2012-07-12 17:33:51