user689842
user689842

Reputation:

Why in a try catch finally, the return is always that of finally?

What happens to the return A code in my catch block?

public class TryCatchFinallyTest {

    @Test
    public void test_FinallyInvocation()
    {
        String returnString = this.returnString();
        assertEquals("B", returnString);
    }

    String returnString()
    {
        try
        {
            throw new RuntimeException("");
        }
        catch (RuntimeException bogus)
        {
            System.out.println("A");
            return "A";
        }
        finally
        {
            System.out.println("B");
            return "B";
        }
    }
}

Upvotes: 4

Views: 203

Answers (5)

Arun Kumar
Arun Kumar

Reputation: 6794

Before return "A" , finally block would be called which will return "B" and your return "A" would be skipped and would never be executed. Its because finally block is always executed before return statement of the method, and if you are returning something from finally block then the return statement of your try/catch would always skipped.

Note : Returning from finally block is not a good practice for a Java programmer. JAVA Compiler also show you the warning as "finally block does not complete normally" if you are returning something from finally block.

Upvotes: 0

greatmajestics
greatmajestics

Reputation: 1093

Finally

You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method.

References http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

Maybe return "A"; is optimized away by the compiler, maybe not and "A" is just dynamically replaced. In fact it doesn't matter as you should not have this code.

This is one of the classical examples of problems with using finally for control flows : you lose some instructions and another coder might not see the "intent" (in fact it can only be a bug or a mischief).

You may have noted that javac issues a warning "finally block does not complete normally".

Don't return in a finally clause

Upvotes: 3

Alex Coleman
Alex Coleman

Reputation: 7326

The finally get's executed right before any return's / exits from the method. Therefore, when you do

return "A";

it executes like so:

System.out.println("B");//Finally block
return "B";//Finally block
return "A";//Return from exception catch

And thus the "B" is returned, not the "A"

Upvotes: 3

cjBucketHead
cjBucketHead

Reputation: 75

the finally block will always be executed, while the catch block is only executed if there's an exception caught.

Upvotes: 0

Related Questions