0

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

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.