Finally block execute or not if insert a return statement inside try block

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

My initial thoughts:
I think so. If there is an exception raised inside the try block before the return statement, then it suppose to go to the catch block, hence the finally block.

Solution:
Yes, it will get executed.
The finally block gets executed when the try block exists. However, even when we attempt to exit within the try block (normal exit, return, continue, break or any exception), the finally block will still be executed.

	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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: