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.)