finally block in Java

In this article, we will discuss finally-block in detail with explanation and example

finally block:

  • finally-block is used to perform clean-up activities or code clean-up like closing database connection & closing streams or file resources, etc
  • finally-block is always associated with try-catch block
  • finally-block can be used in 2 combinations
  • One is try-block is followed by finally-block and other is try-catch-finally sequence
  • The only other possible combination is try-block followed by multiple catch-block and one finally-block at the end
  • Advantage: The beauty of finally block is that, it is executed irrespective of whether exception is thrown or NOT (using try block)
  • Also, it gets executed whether respective exception is handled or NOT (using catch-block)
  • Note: finally-block won’t get executed if JVM exits with System.exit() or due to some fatal error like code is interrupted or killed

Various possible combinations for finally block:

Pseudo code combo 1: finally block follows try block

try {

	// code which might raise exception
}
finally {

	// finally block always gets executed for code clean-up activities
	// irrespective of whether exception raised or NOT
	// irrespective of whether exception is handled or NOT
}

Pseudo code combo 2: finally block follows try-catch blocks

try {

	// code which might raise exception
}
catch(Throwable t) {

	// corresponding handling code, if any exception from try block
}
finally {

	// finally block always gets executed for code clean-up activities
	// irrespective of whether exception raised or NOT
	// irrespective of whether exception is handled or NOT
}

Pseudo code combo 3: finally blocks follows try with multiple blocks

try {

	// code which might raise exception
}
catch(RuntimeException rtex) {

	// corresponding handling code, if any exception from try block
}
catch(Exception ex) {

	// corresponding handling code, if any exception from try block
}
catch(Throwable t) {

	// corresponding handling code, if any exception from try block
}
finally {

	// finally block always gets executed for code clean-up activities
	// irrespective of whether exception raised or NOT
	// irrespective of whether exception is handled or NOT
}

 

Let us see some examples for various cases of finally block

Examples on finally block for various cases:

Case 1: Exception is not raised; finally block executes

FinallyBlockExample1.java

package in.bench.resources.exception.handling;

public class FinallyBlockExample1 {

	public static void main(String[] args) {

		try {

			// code which might raise exception

			int result = 18/3;
			System.out.println("Result of division : "
					+ result);
		}
		catch(ArithmeticException aex) {

			// corresponding handling code, 
			// if any exception from try block

			System.out.println(aex.toString());
		}
		finally {

			// finally block always gets executed 
			// for code clean-up activities

			System.out.println("finally block"
					+ " always gets executed");
			// rest of the code clean-up
		}
	}
}

Output:

Result of division : 6
finally block always gets executed

 

Case 2: Exception is raised and it is caught in the catch block and finally block executes

FinallyBlockExample2.java

package in.bench.resources.exception.handling;

public class FinallyBlockExample2 {

	public static void main(String[] args) {

		try {

			// code which might raise exception

			int result = 19/0;
			System.out.println("Result of division : "
					+ result);
		}
		catch(ArithmeticException aex) {

			// corresponding handling code, 
			// if any exception from try block

			System.out.println(aex.toString());
		}
		finally {

			// finally block always gets executed 
			// for code clean-up activities

			System.out.println("finally block"
					+ " always gets executed");
			// rest of the code clean-up
		}
	}
}

Output:

java.lang.ArithmeticException: / by zero
finally block always gets executed

 

Case 3: Exception is raised but it isn’t caught, as there is no corresponding catch block; still finally block executes

FinallyBlockExample3.java

package in.bench.resources.exception.handling;

public class FinallyBlockExample3 {

	public static void main(String[] args) {

		try {

			// code which might raise exception

			int result = 19/0;
			System.out.println("Result of division : "
					+ result);
		}
		catch(NumberFormatException nfex) {

			// corresponding handling code, 
			// if any exception from try block

			System.out.println(nfex.toString());
		}
		finally {

			// finally block always gets executed
			// for code clean-up activities

			System.out.println("finally block"
					+ " always gets executed");
			// rest of the code clean-up
		}
	}
}

Output:

finally block always gets executed
Exception in thread "main" java.lang.ArithmeticException:/ by zero
	at in.bench.resources.exception.handling
	.FinallyBlockExample3.main(FinallyBlockExample3.java:11)

Explanation:

  • As there is no corresponding catch block present for Arithmetic exception; therefore method creates exception object with information such as name, description, location and passes over to the caller
  • Caller in this case is JVM, which again pass the control over to Default exception handler along with exception object
  • Default exception handler prints the exception information and then method terminates abnormally

 

Case 4: Exception is raised but it isn’t caught, as there is no catch block; finally block executes

FinallyBlockExample4.java

package in.bench.resources.exception.handling;

public class FinallyBlockExample4 {

	public static void main(String[] args) {

		try {
			// code which might raise exception
			int result = 19/0;
			System.out.println("Result of division : "
					+ result);
		}
		finally {
			// finally block always gets executed 
			// for code clean-up activities
			System.out.println("finally block"
					+ " always gets executed");
			// rest of the code clean-up
		}
	}
}

Output:

finally block always gets executed
Exception in thread "main" java.lang.ArithmeticException:/ by zero
	at in.bench.resources.exception.handling
	.FinallyBlockExample4.main(FinallyBlockExample4.java:11)

Explanation:

  • This is similar to above case 3
  • In case 3, there is a catch block but it isn’t a matching one
  • But here as such there is no catch block
  • This is the case of try block followed by finally block

 

finally block never executes:

Case 5: Exception is not raised but finally block won’t gets executed because of explicit Sytem.exit(); method

FinallyBlockExample5.java

package in.bench.resources.exception.handling;

public class FinallyBlockExample5 {

	public static void main(String[] args) {

		try {
			// code which might raise exception
			int result = 18/3;
			System.out.println("Result of division : "
					+ result);

			// explicit kill of program
			System.exit(0);
		}
		catch(ArithmeticException aex) {
			// corresponding handling code, 
			// if any exception from try block
			System.out.println(aex.toString());
		}
		finally {
			// finally block always gets executed 
			// for code clean-up activities
			System.out.println("finally block"
					+ " always gets executed");
			// rest of the code clean-up
		}
	}
}

Output:

Result of division : 6

Explanation:

  • In this case, alternate handling code is provided for Arithmetic exception
  • But, it doesn’t raises any exception but then too finally block won’t gets executed
  • Because of providing System.exit(); statement which kills the code
  • In these kind of scenarios, finally block never gets executed

 

References:

 

Read Also:

 

Happy Coding !!
Happy Learning !!

Various methods to print exception information in Java
try-catch block in Java