1

When try , finally combination is used, in try if there is a return statement.Why is finally block executed first?


class Palindrome
{
    public static void main(String args[]) 
    { 
        System.out.println(Palindrome.test()); 
    }

    public static int test()
    {
        try {  
                //return 0;  
                return 100;
        }  
        finally {  
            System.out.println("finally trumps return.");
        }
    }
}

In the above code please tell me the flow of execution. I know that finally will be executed mandatorily after the try block.But in try block, return staatement will take the control to main class. In that case how will the control come to finally block?

4
  • 2
    in less amount of effort you could have verified it manually Nov 25, 2014 at 2:24
  • @JigarJoshi: How do you verify a "why" question?
    – Thilo
    Nov 25, 2014 at 2:30
  • 3
    The finally block will always be executed if you enter the try block. Them's the rules.
    – Hot Licks
    Nov 25, 2014 at 2:36
  • 1
    If you want to know how, dump the bytecodes.
    – Hot Licks
    Nov 25, 2014 at 2:37

4 Answers 4

7

What do you mean by "first"?

The finally runs before execution leaves the method. When else should it run? It is, after all, part of the method.

But if you have

int x = 1;
try{
   return x;
} finally {
   x = x + 1;
}

then the method will still return 1. So the return statement does get executed before the finally block in a way (to determine the return value).

If the question is why the finally block is executed at all, well, that's what they are for: To "finally" run after the "try" block is done, no matter what.

But in try block, return statement will take the control to main class. In that case how will the control come to finally block?

How? Well, that's just how the language (and runtime) work.

Before control flow is returned to the calling method, the finally block is executed.

It technically even has the option to change the return value (by having its own return statement), but that is highly discouraged.

5
  • In my code , from the main method, the control is directly going to the finally block. But not into try block. I am confused with the flow of execution.Ideally when return statement is in the try block, the control should move out of the try block right?
    – Saicharan
    Nov 25, 2014 at 2:36
  • It goes into the try block first. That is why the method returns 100. Where else would that number come from? Put another println before the return. It will print before the one from the finally block.
    – Thilo
    Nov 25, 2014 at 2:41
  • Thanks for the answer that I 'm looking for - Before control flow is returned to the calling method, the finally block is executed
    – Saicharan
    Nov 25, 2014 at 2:41
  • The output for the above code is finally trumps return. 100 My question is why is it printing the SOP that is in finally block prior to the try block .
    – Saicharan
    Nov 25, 2014 at 2:44
  • There is no printing in your try block. You print from the calling method (and that happens after the method returns, after the finally block).
    – Thilo
    Nov 25, 2014 at 2:46
2

From https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Finally block is to design to always execute:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

If you return in try block and code in finally block is not executed, this is not "always executes".

This makes code more readable if we do something necessary in finally block like unlock lock ,cleanup resources,which prevent some other new programmer(or yourself) add some code that returns or introduces exceptions in try block but without cleaning up the resources.

public static void main(String[] args) throws IOException {
    InputStream is;
    try {
        is = getInpustStreamFromNetwork();
        int i = 1 / 0;// 1. Intruduces exceptions
        return;// 2. returns before clean up resources
    } finally {
        is.close();// clean up resources is important, so it is a good practice to put it into finally block even though there is no exceptions to catch.
        System.out.println("no matter #1 or #2 ,this will be executed\n,");
    }
}
0

Because that's the definition of a finally block. It always happens, regardless of how the block is exited. Finally blocks exist for operations that SHOULD always be performed, like closing open streams and cleaning up socket connections. No matter how the block is exited, the code within the finally block should always be performed. If you want to skip code if the try block is exited successfully, then it belongs in a catch() block with an appropriate exception type.

0

From https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated

There are some cases were the finally block may not execute. Follow the link to see what those are.

Thus the answer to your question is by design. Java is designed to work that way.

2
  • Thanks for the answer, is there any design pattern involved for this design ?
    – Saicharan
    Nov 25, 2014 at 2:38
  • NOthing you do. It is how the language is designed to operate by SUn now Oracle.
    – R Schultz
    Nov 25, 2014 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.