Register now or log in to join your professional community.
For the return statement, it'll stop executing the method block and exit. Ater the exit, the returned value will go to the method that called the method with that method block. For example, "System.out.println(string.length());"
CASE1) If we write return at the end of the try block and no exception occurs,the finally block will execute and then the control return.
CASE2) If we write System.exit(0) at the end of try block,the control immediately goes out of the program and thus finally never executes.
Finally block ll excute If you call the return statement from any of the try or catch block, but its not when we put System.exit on try or catch block. Becouse System.exit will quit the program to run further.
If return is called in try or catch, finally block will execute
wherease calling System.exit(0) will cause termination current thread no matter what goes after it.
Case1 : return in try or catch = finally block will execute
Case2 : System.exit(0) = will terminate current thread execution irrespective of what is expected from specification of flow.
The finally block will execute under all the conditions except for Sytem.exit(0) or you shutdown the JVM itself. So, even if there is a return statement in try block or catch block, finally block will still be executed.
If you call return from catch it will still execute finally
But if call system.exit then it will not execute finally block