有一個類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