Question

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?

Was it helpful?

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.

OTHER TIPS

There are so many explanations about the finally block in a try-catch-finally statement. Go and search for it.

Quick explanation anyway: The finally block is always run, regardless whether an exception was thrown (and maybe caught) or not. If a finally block terminates in an unnormal way (such as itself throwing an excpetion or returning a value) this will always override what was done in the try block or a catch block. That also means that these are got lost.

The conclusion: Never throw an exception ot return a value from the finally block. Only use it for cleaning up processes.

try this. If you are throwing an exception than there is something wrong with object. just return it before the catch.

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

}

Returning from finally is a bad practice in java. It may result in many unexpected outputs. Check below link for some of such examples: http://www.cs.arizona.edu/projects/sumatra/hallofshame/

Anyways found few links related to this finally block, Follow the below links for answers related to that. Does finally always execute in Java? Returning from a finally block in Java

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top