Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A curious output with finally

 
A. M. Anisul Huq
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21000
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic