• support@answerspoint.com

Does finally always execute in Java?

1565

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 8 years ago
  • Sandy Hook

0

//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
  • answered 8 years ago
  • Sunny Solu

Your Answer

    Facebook Share        
       
  • asked 8 years ago
  • viewed 1565 times
  • active 8 years ago

Best Rated Questions