java異常處理機制
1)在java語言中,通常將可能出現異常的語句放入try{}語句中,將出現錯誤后需要執行的語句放入到catch{}語句中,將無論是否發生異常都要執行的語句放在finally{}語句中。
2)當程序執行出現異常的時候,系統會拋出一個異常,然后由try{}語句中中出現異常的地方轉到catch{}語句中。不過不管有沒有異常產生,finally{}中的語句都將執行。
3)如果系統出現系統錯誤或者運行Runtime異常,jvm會結束程序運行,不一定會執行finally{}中的語句。
4)如果try{}中產生的異常在catch中沒有處理,系統將停止程序,也不會執行finally中的語句。
多層異常處理
public class CatchWho {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("發生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch");
}
}
}
程序運行結果:
ArrayIndexOutOfBoundsException/內層try-catch
發生ArithmeticException
分析:在本程序中,一個外部try{}catch{}語句中嵌套了一個try{}catch{}語句。內部的try{}語句中拋出一個ArrayIndexOutOfBoundsException,然后內部的catch{}語句捕捉到該異常並進行處理。然后外部try{}語句中拋出一個ArithmeticException異常,外部catch{}捕獲異常進行處理。在程序中可以看到,外部共有兩個catch{}語句。一個用來捕獲ArrayIndexOutOfBoundsException異常,另一個用來捕獲ArithmeticException,可是最后結果卻是外部catch並沒有捕獲ArrayIndexOutOfBoundsException,只捕獲了ArithmeticException異常,這是因為在內部的catch語句中已經將ArrayIndexOutBoundsException處理了。再來看以下代碼:
public class CatchWho2 {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArithmeticException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("發生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch");
}
}
}
運行結果
ArrayIndexOutOfBoundsException/外層try-catch
分析:在此程序中,內部try{}拋出的異常ArrayIndexOutOfBoundsException在內部catch語句中沒有得到處理,所以外部try{}語句中拋出ArithmeticException的語句並沒有執行,在外部的catch語句中ArrayIndexOutOfBoundsException被捕獲所以執行了第二個catch{}語句中的內容。
多個try{}catch{}finally{}語句嵌套
當有多個try{}catch{}finally{}語句嵌套使用的首,根據異常在不同層次不同位置的拋出,是會造成finally語句不同的執行結果,這里的情況比較多,較為繁瑣不做具體分析,但是總體原則是:一個異常拋出的語句到捕獲這個異常的catch語句之間的語句,不論是try,catch,finally語句都不會執行。
關於finally語句是否一定會執行
請看以下代碼:
public class SystemExitAndFinally {
public static void main(String[] args)
{
try{
System.out.println("in main");
throw new Exception("Exception is thrown in main");
}catch(Exception e) {
System.out.println(e.getMessage());
System.exit(0);
}finally{
System.out.println("in finally");
}
}
}
執行結果為:
in main
Exception is thrown in main
可見也不是任何情況下finally語句中的代碼都會執行,此次是因為在處理異常的catch代碼中執行了退出的方法。