Reputation: 4532
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.
when the 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 :
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
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
Upvotes: 0
Views: 184
Reputation: 10871
In Example 1
:
You perform int a=2/0;
This will throw java.lang.ArithmeticException
as you are dividing a number by zero
.
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
In Example 2:
You perform int a=2/1;
So there is no problem at all.
After executing the above line, your program executed System.exit(0);
. So No chance of executing the finally block. That is the reason you don't get any output in this case.
Upvotes: 1
Reputation: 1479
In the first snippet, there is Divide-by-zero error and so the System.exit() is not even called. In the second snippet System.exit() is called and so the JVM exited
Upvotes: 1