Skip to main content
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Does a finally block always get executed in Java?

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("I don't know if this will get printed out");
}

Answer*

Cancel
9
  • 22
    FYI: In C# the behaviour is identical apart from the fact that replacing the statement in the finally-clause with return 2; is not allowed (Compiler-Error).
    Alexander Pacha
    –  Alexander Pacha
    2013-10-31 08:08:33 +00:00
    Commented Oct 31, 2013 at 8:08
  • 15
    Here is an important detail to be aware of: stackoverflow.com/a/20363941/2684342
    WoodenKitty
    –  WoodenKitty
    2013-12-03 23:37:57 +00:00
    Commented Dec 3, 2013 at 23:37
  • 25
    You can even add a return statement in the finally block itself, which will then override the previous return value. This also magically discards unhandled exceptions. At that point, you should consider refactoring your code.
    Zyl
    –  Zyl
    2015-04-15 17:25:33 +00:00
    Commented Apr 15, 2015 at 17:25
  • 10
    That does not really prove that finally trumps return. The return value is printed from the caller code. Doesn't seem to prove much.
    Trimtab
    –  Trimtab
    2016-06-21 04:20:19 +00:00
    Commented Jun 21, 2016 at 4:20
  • 23
    Sorry, but this is a demonstration not a proof. It is only a proof if you can show that this example always behaves this way on all Java platforms, AND that similar examples also always behave this way.
    Stephen C
    –  Stephen C
    2017-08-20 01:24:21 +00:00
    Commented Aug 20, 2017 at 1:24

Morty Proxy This is a proxified and sanitized view of the page, visit original site.