ProAnswers.org

Does finally always execute in Java?

I have a try/catch block with returns inside it. Will the finally block be called?
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.”);
}

finally will be called all ways if we write in the program.

 

The only time finally won't be called is if you call System.exit() or if the JVM crashes first.
//proof code

 

class Test

{

    public static void main(String args[]) 

    { 

     System.out.println(Test.test()); 

    }

 

    public static int test()

    {

     try {  

             return 0;  

     }  

     finally {  

         System.out.println("finally trumps return.");

     }

    }

}

 

output:

 

finally trumps return. 

0