Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java try-finally return design question

Tags:

java

In Java, a try { ... } finally { ... } is executed somewhat unintuitively to me. As illustrated in another question, Does finally always execute in Java?, if you have a return statement in the try block, it will be ignored if a finally block is defined. For example, the function

boolean test () {     try {         return true;     }     finally {         return false;     } } 

will always return false. My question: why is this? Is there a particular philosophy behind this design decision made by Java? I appreciate any insight, thank you.

Edit: I'm particularly interested as to 'why' Java thinks it's ok to violate the semantics that I define. If I 'return' in a try block, the method should return right then and there. But the JVM decides to ignore my instruction and return from a subroutine that actually hasn't yet been reached.

like image 512
Travis Webb Avatar asked Nov 15 '10 14:11

Travis Webb


People also ask

Can you return in a try catch Java?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned.

Does finally run if return in try?

Java For TestersYes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

Can we use return statement in try catch or finally block?

Yes, we can write a return statement of the method in catch and finally block.

What will happen when try and finally block both return value?

When try and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by try block.


2 Answers

Technically speaking, the return in the try block won't be ignored if a finally block is defined, only if that finally block also includes a return.

It's a dubious design decision that was probably a mistake in retrospect (much like references being nullable/mutable by default, and, according to some, checked exceptions). In many ways this behaviour is exactly consistent with the colloquial understanding of what finally means - "no matter what happens beforehand in the try block, always run this code." Hence if you return true from a finally block, the overall effect must always to be to return true, no?

In general, this is seldom a good idiom, and you should use finally blocks liberally for cleaning up/closing resources but rarely if ever return a value from them.

like image 105
Andrzej Doyle Avatar answered Nov 02 '22 05:11

Andrzej Doyle


If code in finally block ends abruptly, it changes return value/exception from try block. This is considered to be bad practice, and you should not do that.

Among other places, this is also discussed in Java Puzzlers book.

like image 41
Peter Štibraný Avatar answered Nov 02 '22 06:11

Peter Štibraný