Does finally always execute in Java?

Total Post:145


 1194  View(s)
Rate this:
I have a try/catch block with returns inside it. Will the finally block be called?

For example:

try {  
    return success;  
catch (Exception e) {   
    return failure;  
finally {  
    System.out.println("i don't know if this will get printed out.");
I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question.
  1. Re: Does finally always execute in Java?

    finally will be called.

    The only times finally won't be called are:
    1.if you call System.exit() or
    2.another thread interrupts current one or
    3.if the JVM crashes first     

    Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:
    try { return true; } finally { return false; }
    Same thing with throwing exceptions from the finally block 

      Modified On May-08-2015 06:54:17 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.