Home > DeveloperSection > Forums > Does finally always execute in Java?
ezra heywood
ezra heywood

Total Post:145

Posted on    May-08-2015 1:19 AM

 Java Exception Handling  Java 

 1 Reply(s)
 403  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.

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    May-08-2015 6:52 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick