File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes A curious output with finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "A curious output with finally" Watch "A curious output with finally" New topic

A curious output with finally

A. M. Anisul Huq

Joined: Aug 11, 2009
Posts: 13
The following code:

has an output 4. Why? Why isn't it 2? What happens to the return statement inside try?
Rafael Prado Oliveira

Joined: Apr 30, 2013
Posts: 28
Finally will be always executed no matter what.

You ask him to return 1, but the method sees a Finally, it will execute the return of the Finally that is 4.

Run the code bellow you will understand better

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45429
That code won’t compile or run.

This question shows what bad design it can be to use return in a finally statement.
Henry Wong

Joined: Sep 28, 2004
Posts: 20380

Surprisingly, the JLS actually does a good job at explain this...


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

That code is useful for demonstrating how finally works, but it's worth noting that in real code you should never return, throw, break, or continue out of finally. We don't want finally's completion to obscure how the "real work" completed, which is exactly what it's doing in this example.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45429
Don’t go back and correct errors in old posts. It makes the replies look like nonsense.
Your code still won’t run. Maybe for a+2 you meant to write a += 2;
I agree. Here's the link:
subject: A curious output with finally
It's not a secret anymore!