Returning From Finally Block

Here I am posting another very strange fact about java. I mentioned something about exit points in my short and sweet post

In this post, I’ve stated that exceptions can be considered as exit points from a method. Well that is true, EXCEPT FOR ONE CASE. The only exception to this statement can be returning a value from finally block or throwing and exception from the finally block.

Use of Finally Block

I’m sure you know what finally blocks are used for. Somethings need to be done, no matter what the control flow is. Resources like database connections once opened, need to be closed. Thus, the statements used for closing contexts and connections are usually placed in the finally block. e.g. 

Connection conn = null; 
try { 
    conn = getConnection(); 
    // Logic goes here 
} catch(Exception e) { 
    LOG.error("Failed to connect to the databse", e); 
} finally { 
    if (!conn.isClosed()) { 

Explanation With Examples

Consider the following code..

public String returnFromFinally() throws Exception { 
    try { 
        throw new Exception(); 
    } catch (Exception e) { 
        throw new Exception(); 
    } finally { 
        return "someRandomString"; 

Here, instead of throwing the exception twice, the method will always return the string “someRandomString” successfully. That is because,

The exit points in finally block always override other exit points in the method.

Similarly, the following code can be considered to be an infinite loop.

while (true) { 
    try {         
    } finally { 

The java compilers optimize the following code to be an infinite loop. Since the return statement in try block will be overridden by the continue statement in finally block, resulting in an infinite loop.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: