[英]Exception raised within a try/catch block (Java)
我幾周前才開始學習Java。 我從我的教科書中讀到,它說:如果在執行一個代碼塊的中途發生異常,該代碼塊被“ try”塊包圍,然后跟隨着幾個“ catch”子句(具有自己的代碼塊), try塊的其余部分將被跳過,如果有一個catch子句與異常類型匹配,則將執行與catch子句關聯的塊。 但是,如果沒有匹配的catch子句怎么辦? 什么都不會執行,也不會發生任何特定情況? 我了解這只是一個簡單的問題,但找不到任何答案。 謝謝你的幫助。
如果不存在任何捕獲塊來捕獲指定的異常,則該錯誤將向上拋出(好像您周圍沒有try / catch系列)。 如果存在finally塊,則當然仍將執行它。
我會盡力為您解釋。
這是引發異常的方法的示例:
public void anExceptionThrowingMethod() {
throw new Exception("Uh oh an exception occurred!");
}
如果我們嘗試這樣調用此方法:
anExceptionThrowingMethod();
您的程序將崩潰,並且您將得到錯誤:
java.lang.IllegalArgumentException: Uh oh an exception occurred!
這是因為當我們調用該方法時,我們沒有處理發生錯誤的情況。 為此,我們使用try{ } catch { }
塊:
try {
anExceptionThrowingMethod();
} catch(Exception e) {
System.out.println("We handled the exception!");
}
該程序現在將不再崩潰,並且將打印:
We handled the exception!
當您運行此代碼時,異常引發方法將引發異常。 該異常將由catch塊捕獲,並且堆棧跟蹤將被打印出。 異常拋出方法之后將不執行任何代碼:
try {
anExceptionThrowingMethod();
// Nothing will be executed after this
} catch(Exception e) {
// Instead, this catch block will be executed
System.out.println("We handled the exception!");
}
如果您總是想執行一些代碼,即使發生了異常,也可以使用finally塊:
try {
anExceptionThrowingMethod();
// Nothing will be executed after this
} catch(Exception e) {
// Instead, this catch block will be executed
System.out.println("We handled the exception!");
} finally {
// This block will always be executed, regardless of whether an exception has occurred.
}
如果存在多個異常類型,則可以捕獲超類Exception
,也可以分別處理每個單獨的異常類型:
try {
manyExceptionThrowingMethod();
// Nothing will be executed after this
} catch (InterruptedException e) {
// Called when an InterruptedException occurs
e.printStackTrace();
} catch (IllegalArgumentException e) {
// Called when an IllegalArgumentException occurs
e.printStackTrace();
} finally {
// This code will always be executed, regardless of whether an exception has occurred.
}
如果您不處理異常類型,則發生該錯誤時程序將崩潰
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.