• support@answerspoint.com

Does finally always execute in Java?

509

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.

2Answer


0

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 (via the interrupt method) or
  3. if the JVM crashes first
  • answered 2 years ago
  • Sunny Solu

0
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
  • answered 2 years ago
  • G John

Your Answer

    Facebook Share