Problem
In Java, does the finally block gets executed if we insert a return statement inside the try block of a try-catch-finally?
Solution
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)); return; } catch (FileNotFoundException e) { System.out.println("File Not Found!"); } finally { System.out.println("finally!"); } } public static void main(String[] args) { foo(""); }
OUTPUT:
File Not Found!
finally!
References
http://tianrunhe.wordpress.com/2012/04/15/finally-block-execute-or-not-if-insert-a-return-statement-inside-try-block/
http://stackoverflow.com/questions/12156504/does-code-in-a-finally-get-executed-if-i-have-a-return-in-my-catch-in-c
http://stackoverflow.com/questions/7143788/try-catch-finally-in-java
http://stackoverflow.com/questions/3715198/will-finally-blocks-be-executed-if-returning-from-try-or-catch-blocks-in-c-if
0 comments:
Post a Comment