2013-12-11 54 views
0

請原諒我這裏的這類問題,但我一定會得到很好的解釋與樣品,這將使對java有更好的理解。Java - 異常處理和強制完全退出系統

System.exit(0);得到執行時,系統會中斷執行流程並將其傳出系統。這是我的理解是的,但現在我已經碰到一些事情來了,如同下面:

Example 1 : 

class FinallySystemExit 
{ 
public static void main(String args[]) 
{ 
try 
{ 
int a=2/0; 
System.exit(0); 
} 
catch(Exception e) 
{ 
System.out.println("i am in catch block"); 
} 
finally 
{ 
System.out.println("finally"); 
} 
} 
} 

我對上面的代碼的理解是它不會打印從系統中任何東西,exit但產量:

i am in catch block 
finally 

Example 2 

class FinallySystemExit 
{ 
public static void main(String args[]) 
{ 
try 
{ 
int a=2/1; 
System.exit(0); 
} 
catch(Exception e) 
{ 
System.out.println("i am in catch block"); 
} 
finally 
{ 
System.out.println("finally"); 
} 
} 
} 

當我執行上述代碼it prints nothing

兩個程序之間的差異是:

First Program : 

int a=2/0; 

Second Program : 

int a=2/1; 

我完全糊塗了,我的基本的瞭解這裏被打破。

請問有人能解釋一下原因。

由於

+1

謝謝你們,我現在明白了。 – SAR

回答

1

Example 1: 您執行int a=2/0;

這將引發java.lang.ArithmeticException因爲你是dividing a number by zero。 當你的代碼是由try - catch包圍異常被捕獲,並在catch block印刷的發言,並去finally

Example 2: 您執行int a=2/1; 因此,有一點問題都沒有。

執行完上述行後,程序執行System.exit(0);。所以沒有機會執行finally塊。這就是你在這種情況下沒有得到任何輸出的原因。

1

在第一片段中,有除以零誤差等等System.exit()的甚至不被調用。在第二個片段System.exit()的調用等等JVM退出