Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call return statement or System.exit on try or catch block

Tags:

java

I got the following question asked in interview :

What will happen if one calls a return statement or System.exit on try or catch block ? Will finally block execute?

Does the finally block always get executed?

EDIT: After trying the above in java:

  1. finally block executes if I put return statement in try block or catch block but

  2. finally block doesn't run if I call System.exit form try or catch.

I don't get the reason behind though.

like image 922
Abhishek Bhatia Avatar asked Aug 17 '14 05:08

Abhishek Bhatia


People also ask

What happens if you put return statement system exit () on a try catch block?

Answer of this question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System. exit() from try or catch block.

Can you have a return statement in a try or catch block?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.

What happens if I put system out in catch block?

It will throw an exception and will stop the execution of program . Else put a try catch inside the catch block, or the exception will be propagated to JVM. It will throw an exception and will stop the execution of program.

When we call system exit () method in TRY block does finally block gets executed?

If we call the System. exit() method explicitly in the finally block then only it will not be executed. There are few situations where the finally will not be executed like JVM crash, power failure, software crash and etc. Other than these conditions, the finally block will be always executed.


1 Answers

What will happen if one calls a return statement or System.exit on try or catch block ?

Will finally block execute?

In the case of a return, Yes. If you want the gory details, they are specified in JLS section 14.20.2.

(Note that in the JLS terminology, a return counts as an abrupt termination. But that doesn't matter, because when you analyse the spec carefully, you will see that the finally gets executed for both normal and abrupt terminations.)

In the case of a System.exit(), No. The call to the exit method never returns, and it doesn't throw an exception either. Therefore the "enclosing" finally clauses for the thread never get executed.

(In JLS parlance, the exit() call doesn't "terminate" at all. It conceptually the same as a method going into an infinite loop that (magically) doesn't use any CPU time. All of the activity associated with JVM shutdown happens on other threads.)

like image 115
Stephen C Avatar answered Sep 28 '22 07:09

Stephen C