Saturday, April 5, 2014

Finally block and return statement


In Java, does the finally block gets executed if we insert a return statement inside the try block of a try-catch-finally?


The answer is yes, both in java and c#.

In java, the only time a finally block will not be executed is when you call exit() OR for some reason JVM crashes, before finally is reached. The exit() call will shutdown the JVM, so no subsequent line of code will be run.

In c#, the answer is yes, but if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up. For more information, see Unhandled Exception Processing in the CLR.

Now, lets stick to Java.

The point of executing finally block at the end is to allow you to release all the acquired resources. Now, there are 2 cases:
  • no exception in the try block  -  the program execution goes to finally block and then we return. So, finally executes before return.
  • There is exception - In this case, exception is raised, we go to catch block and finally is executed after that.

So, whenever there is exit within the try block (normal exit, return, continue, break or any exception), the finally block will still be executed.

Java code - Here the file doesn't exits - 
public static void foo(String fileName) {
    File file = new File(fileName);
    try {
        new BufferedReader(new FileReader(file));
    } catch (FileNotFoundException e) {
        System.out.println("File Not Found!");
    } finally {
public static void main(String[] args) {

File Not Found!



Post a Comment