Search code examples
javaeclipsetry-catch-finally

return statement - finally block does not complete normally


Similar question has been asked here. But that does not provide answer.

try {
        object = (Dev)Class.forName("Dev").newInstance();
    } catch (Exception e) 
    {
        throw new RuntimeException("Devis not available");
    }
    finally
    {
        return object;  
    }

But finally block gives warning :

finally block does not complete normally

But as per my understating, finally block always gets executed and will return the object. Why warning says that it will not get completed normally?


Solution

  • The problem is that the finally block would remove any exceptions being thrown since it would issue a "normal" return.

    From the JLS spec:

    Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

    and (more relevant in your case):

    Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.