finally block execution

Description:

Is a finally block executed when an exception is thrown from a try block that does not have a catch block, and if so, when?

Solution:

A finally block is executed even if an exception is thrown or propagated to the calling code block.

Example:

public class FinallyExecution {
	public static void main(String[] args) {
		try{		
			FinallyExecution.divide(100, 0);}
		finally{
			System.out.println("finally in main");
		}
	}
	public static void divide(int n, int div){
		try{
			int ans = n/div; }
		finally{
			System.out.println("finally of divide");
		}
	}
}

Output can vary, being either:

finally of divide
finally in main
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at exceptions.FinallyExecution.divide(FinallyExecution.java:20)
	at exceptions.FinallyExecution.main(FinallyExecution.java:9)

…or…

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at exceptions.FinallyExecution.divide(FinallyExecution.java:20)
	at exceptions.FinallyExecution.main(FinallyExecution.java:9)
finally of divide
finally in main
0 answers