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
4
  • 10
    Important to know.
    Aminadav Glickshtein
    –  Aminadav Glickshtein
    2018-07-06 12:06:59 +00:00
    Commented Jul 6, 2018 at 12:06
  • Good to know, and makes sense as well. It seems that actually returning the value of return is what comes after finally. Calculating the return value (printX() here) still comes before it.
    Albert
    –  Albert
    2019-06-26 10:58:06 +00:00
    Commented Jun 26, 2019 at 10:58
  • 2
    Nope. The code above should replace System.out.println("finally trumps return... sort of"); with System.out.print("finally trumps return in try"); return 42;
    Pacerier
    –  Pacerier
    2020-05-10 01:21:29 +00:00
    Commented May 10, 2020 at 1:21
  • This answer is completely self-evident IMO because return doesn't return some magic continuation that only gets evaluated if the caller prints it or whatever. printX() gets called before the return happens, regardless of any try/catch, or anything else.
    Christopher Schultz
    –  Christopher Schultz
    2022-06-09 21:39:30 +00:00
    Commented Jun 9, 2022 at 21:39

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