Table of Contents
*This post may contain affiliate links. As an Amazon Associate we earn from qualifying purchases.
During your IT interview, you may be asked about the behavior of the code in the Java finally block. Let us tell you the main facts about this type of code so that you can provide a complete answer to your interviewers.
Will the code in the finally block run after a return statement has been executed?
The answer to this frequently asked IT interview question is yes. After a return code is executed, the code included in the finally block will take precedence over it. To get a better idea of how this happens, we will provide an example. This way, you will be able to visualize the entire process.
The return of the code listed above is as follows:
finally block is run before the method returns.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 1
According to this output, the finally block has indeed been executed BEFORE our ?System.out.printIn(XClass,proveIt())? statement. The ?1? listed below means that the ?finally block is run before the method returns? statement is true.
Will the code in the finally block always run after a return statement has been executed?
The answer that the interviewers expect from you is no. While in most cases the code in the finally block will run after a return statement has been executed, there are some situations when it will not. It is very important that you know about them so that you can provide a complete answer for your job meeting.
Specific situations when the code in the finally block will not run after return
- You should know that if the System.exit() function is run first, the code in the finally block will NOT run after return.
- If the JVM crashes, then the code will obviously not run after return.
While these situations are rare, you should be able to mention them to the interviewer to make a stellar impression.
A Common Mistake
Including a return statement in the finally block as well as the try block will most likely lead to very confusing situations. The return value included in the finally block will always override the returned values in the try block.
We hope we have provided you with all the information you need about the behavior of the code in the finally block so that you can ace your interview. Good luck on your job meeting from the IT Interview Guide team!