Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: try finally blocks execution [duplicate]

I am confused about the try-finally execution when there exists return; in the try block. In my understanding, the finally block will always be executed, i.e. before returning to the calling method. While considering the following simple code:

public class TryCatchTest {     public static void main(String[] args){         System.out.println(test());     }     static int test(){         int x = 1;         try{             return x;         }         finally{             x = x + 1;         }     } } 

The result printed is actually 1. Does this mean the finally block is not executed? Can anyone help me with it?

like image 839
yifei Avatar asked Aug 08 '13 16:08

yifei


People also ask

Is it possible to take 2 finally blocks for the same try?

You can only have one finally clause per try/catch/finally statement, but you can have multiple such statements, either in the same method or in multiple methods. try.

Does finally block always execute in Java?

A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.

Can we have 2 finally blocks in Java?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.

When finally block gets executed in Java?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.


1 Answers

When you return from try block, the return value is stored on the stack frame for that method. After that the finally block is executed.

Changing the value in the finally block will not change the value already on the stack. However if you return again from the finally block, the return value on the stack will be overwritten, and the new x will be returned.

If you print the value of x in finally block, you will get to know that it is executed, and the value of x will get printed.

static int test(){     int x = 1;     try{         return x;     }     finally{         x = x + 1;         System.out.println(x);  // Prints new value of x     } } 

Note: In case of a reference value being returned, the value of reference is stored on the stack. In that case, you can change the value of object, using that reference.

StringBuilder builder = new StringBuilder(""); try {     builder.append("Rohit ");     return builder;  } finally {     // Here you are changing the object pointed to by the reference     builder.append("Jain");  // Return value will be `Rohit Jain`      // However this will not nullify the return value.      // The value returned will still be `Rohit Jain`     builder =  null; } 

Suggested Read:

  • JVM Specs - Frames
like image 152
Rohit Jain Avatar answered Oct 25 '22 07:10

Rohit Jain