[英]Java - exception handling and force full exit from the system
Please excuse me for this kind of questions here but I am sure to get good explanation with sample which will make to have better understanding about java. 请原谅我这里提出的这类问题,但我肯定会对样本做出很好的解释,以便更好地了解java。
when the System.exit(0);
当System.exit(0);
gets executed, the system will break the execution flow and come out the system. 执行后,系统将中断执行流程并退出系统。 this is what is my understanding as of now but I have came across some thing like the below : 这是我现在的理解,但我遇到了类似下面的事情:
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");
}
}
}
my understanding about the above code is it will not print anything and exit
from the system but the output is : 我对上面代码的理解是它不会打印任何内容并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");
}
}
}
when i execute the above code it prints nothing
当我执行上面的代码时, it prints nothing
The difference between two programs are : 两个程序的区别是:
First Program :
int a=2/0;
and the 和
Second Program :
int a=2/1;
I am totally confused and my basic understanding is broken here. 我完全糊涂了,我的基本理解在这里打破了。
Could some one explain the reason please. 有人可以解释原因吗。
Thanks 谢谢
In the first snippet, there is Divide-by-zero error and so the System.exit() is not even called. 在第一个片段中,存在Divide-by-zero错误,因此甚至不调用System.exit()。 In the second snippet System.exit() is called and so the JVM exited 在第二个片段中调用了System.exit(),因此退出了JVM
In Example 1
: You perform int a=2/0;
在Example 1
:执行int a=2/0;
This will throw java.lang.ArithmeticException
as you are dividing a number by zero
. 当您dividing a number by zero
这将抛出java.lang.ArithmeticException
。 As your code is surrounded by try - catch
the exception is caught and it printed the statement in catch block
and went to finally
block 当你的代码被try - catch
包围时,异常被捕获并且它在catch block
打印语句并转到finally
块
In Example 2:
You perform int a=2/1;
在Example 2:
执行int a=2/1;
So there is no problem at all. 所以没有任何问题。
After executing the above line, your program executed System.exit(0);
执行上面的行后,程序执行System.exit(0);
. 。 So No chance of executing the finally block. 所以没有机会执行finally块。 That is the reason you don't get any output in this case. 这就是你在这种情况下没有得到任何输出的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.