aspose file tools*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "A curious output with finally" Watch "A curious output with finally" New topic
Author

A curious output with finally

A. M. Anisul Huq
Greenhorn

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



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

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
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18989
    
  40

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

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2

Henry


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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
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;
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: A curious output with finally