概念
1.try
如果在一個方法內部出現了異常(或者在方法內部調用的其他方法拋出了異常),這個方法將在拋出異常的過程中結束。
異常處理理論上有兩種基本模型。終止模型和恢復模型。個人理解回覆模型類似於中斷處理。而java支持終止模型,這種模型中,程序無法返回異常發生的地方繼續執行。
要是不希望方法就此結束,可以在方法內設置一個特殊的塊來捕獲異常,成爲try塊。
2.catch
對於拋出的異常必須在某處得到處理,異常處理程序以關鍵字catch表示,緊跟在try後。
3.finally
有一些代碼希望無論有沒有異常拋出都能夠執行,可以在catch後面加finally子句。
4.結構
try{
}catch{
}finally{
}
5.執行順序
a.拋出異常處理順序
public class TestException {
public static void main(String[] args) {
TestException testException1 = new TestException();
int i=1;
try {
i=2;
System.out.println("in try");
testException1.fun();
System.out.println("end try");
} catch (Exception e) {
System.out.println("in catch");
} finally{
i=3;
System.out.println("in finally");
}
System.out.println("the end i="+i);
}
public void fun() throws Exception{
throw new Exception();
}
}
輸出結果:
in try
in catch
in finally
the end i=3
可以看到testException1.fun();拋出異常以後,代碼跳出try塊轉到catch執行異常處理程序,然後繼續執行finally程序。最後順序執行System.out.println("the end i="+i);如果沒有try塊的話,整個方法都會跳出。
b.不拋出異常處理順序
public class TestException {
public static void main(String[] args) {
TestException testException1 = new TestException();
int i=1;
try {
i=2;
System.out.println("in try");
//testException1.fun();
System.out.println("end try");
} catch (Exception e) {
System.out.println("in catch");
} finally{
i=3;
System.out.println("in finally");
}
System.out.println("the end i="+i);
}
public void fun() throws Exception{
throw new Exception();
}
}
結果輸出:
in try
end try
in finally
the end i=3
可以看到不管異常拋不拋出,finally語句都會執行。