DOES FINALLY ALWAYS EXECUTE IN JAVA?

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
 722  View(s)
Ratings:
Rate this:
I have a try/catch block with returns inside it. Will the finally block be called?

For example:

try {  
    something();  
    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. Mayank Tripathi

    Post:397

    Points:3117
    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!