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:
finally
block executes if I put return statement in try block or catch block but
finally
block doesn't run if I call System.exit form try or catch.
I don't get the reason behind though.
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With