2013-12-11 58 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退出