public class ZeroTest
{
public static void main(String[] args)
{
try
{
int i = 100 / 0;
System.out.print(i);
}
catch(Exception e)
{
System.out.print(1);
throw new RuntimeException();
}
finally
{
System.out.print(2);
}
System.out.print(3);
}
}
輸出結果為:12
解析:
1、int
i = 100/ 0; 會出現異常,會拋出異常,System.out.print(i)不會執行,
2、catch捕捉異常,繼續執行System.out.print(1);
3、當執行 throw
newRuntimeException(); 又會拋出異常,這時,除了會執行finally中的代碼,其他地方的代碼都不會執行
深度思考:
還是需要理解Try...catch...finally與直接throw的區別:try catch是直接處理,處理完成之后程序繼續往下執行,throw則是將異常拋給它的上一級處理,程序便不往下執行了。本題的catch語句塊里面,打印完1之后,又拋出了一個RuntimeException,程序並沒有處理它,而是直接拋出,因此執行完finally語句塊之后,程序終止了。
