[英]How to handle an exception in Java thrown by a method into another method?
假設我有這門課:
public class Obj1{
...
public void do_Something(int someParameter) throws SomeException {
if(...) throw new SomeException();
...
}
...
}
然后,某處
public class Obj2{
...
public void do_SomeOtherThing(Obj1 obj1){
obj1.do_Something();
//apparently the only solution is try-catching it directly, even if I'm not in the main...
...
}
我了解到異常應該只由 METHOD 拋出,並由 MAIN 捕獲,所以,我的問題是:try-catch 是處理子方法異常的唯一方法,還是最外部的方法 (do_SomeOtherThing) 會拋出它,這樣我就可以直接在 main 中嘗試捕獲它,刪除 Object2 類中的 try-catch?
基本上,我可以這樣做嗎?
public static void main(String[] args){
Object1 obj1 = new Object1();
Object2 obj2 = new Object2();
try{
obj2.do_SomeOtherThing(obj1);
}
catch(SomeException e){
...
}
}
或不?
已檢查異常是方法與其調用者之間的契約的一部分,拋出的異常總是需要以一種或另一種方式處理。
正確答案取決於具體情況:
String getStringFromRemoteServer() throws IOException { ... }
String getConfigString() {
try {
return getStringFromRemoteServer();
} catch (IOException e) {
LOG.warn("Failed to contact server, using local version.", e);
return getLocalString();
}
}
在這種情況下,我們有一個我們需要的數據的替代來源,所以如果首選方法失敗,我們會捕獲異常,記錄它(以便我們知道我們的網絡存在問題)並調用替代方法。
Configuration parseConfiguration(String configString) throws ParseException { ... }
void loadConfiguration() {
try {
this.globalConfig = parseConfiguration(getConfigString());
} catch (ParseException e) {
throw new RuntimeException("Corrupted config", e);
}
}
在這種情況下,異常意味着我們應用程序的配置被嚴重破壞。 嘗試處理這個錯誤是沒有意義的,我們的任何調用者嘗試處理它也是沒有意義的,所以在loadConfiguration()
上聲明throws
只會造成混亂。 我們將異常包裝在RuntimeException
並重新拋出它。 請注意,我們不記錄它——會有一些未捕獲異常的頂級報告,所以在這里記錄它會重復。
讓parseConfiguration()
拋出已檢查的異常仍然很有價值,因為當我們從交互式配置編輯器調用它時,我們會捕獲異常並向用戶顯示錯誤消息。
int stringToInteger(String s) throws BadNumberException { ... }
String decimalStringToHexString(String s) throws BadNumberException {
return intToHex(stringToInteger(s));
}
在這種情況下,我們不會改變異常的含義decimalStringToHexString
正在從字符串轉換數字,一種可能的結果是該字符串是非法的。 我們的調用者需要意識到這是一個可能的結果,就像stringToInteger()
調用者一樣,所以我們只需聲明異常並讓我們的調用者處理它。 我們的調用者知道他們使用號碼的上下文,因此他們可以決定如何處理異常。
幾條規則:
try { ... } catch (Exception e) {}
空的 catch 子句將很難發現你的代碼為什么不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.