The string returns at the end and tries to block

I came across this question and I can not understand the reason for the conclusion that it gives.

Program:

public static String method(){ String s = new String(); try { s = "return value from try block"; return s; } catch (Exception e) { s = s + "return value from catch block"; return s; } finally { s = s + "return value from finally block"; } } 

Output:

return value from try block

Now I debugged it, and the value s in return s in the try block was return value from try block , return value from catch block after it returned from finally block .

Nevertheless, the conclusion:

return value from try block

Can someone explain this behavior?

+5
source share
3 answers

First of all, let's understand how Java handles method calls. Each thread has a separate stack memory. When we call a method, Java internally inserts the record on top of the stack. The record contains some details, such as parameters and an object, etc.

There is one interesting field here: the return value. When a return statement is encountered, the field is updated. Now follow the code.

In the try block, the return value field is set to the return value from the try block. Now, according to the execution sequence, the finally block is executed. Now the finally block changes the reference to the string s . It did not change the return value field that was previously set by the try block. Finally, the method call is completed, and Java internally issues a record and returns a return value field. Therefore, it returns the return value from the try block.

If the finally block returns the string after modification, the return value field will be updated again, and the updated string will be returned.

+1
source

Avoid return statement in a try block if you include finally in your code, rather than using it at the end of the method. In addition, you cannot change the value of the returned variable in the finally block. See fooobar.com/questions/318885 / ...

-1
source

finally,

finally used in the try / catch statement to execute the code "always"

 lock.lock(); try { //do stuff } catch (SomeException se) { //handle se } finally { lock.unlock(); //always executed, even if Exception or Error or se } 

Java 7 introduced a new attempt with the resource operator, which can be used to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable

-2
source

Source: https://habr.com/ru/post/1268519/


All Articles