Java finally block in Exception handling


Finally block

It is one of the block in which we write the block of statements which will relinquish (released or close or terminate) the resource (file or database) where data store permanently.

Important points about finally block

  • Finally block will execute compulsory
  • Writing finally block is optional.
  • It is highly recommended to the java programmer to write on finally block for the entire java program.
  • In some of the circumstances one can also write try and catch block in finally block.
ecxeption4

Finally block : Syntax

		

try
{
	-----------
	----------
}
catch (Exception)
{
	-------------
	------------
}

final
{
	
}
 	

Tip 1 : Finally block is optional

In the program we can have minimum zero and maximum one finally statement.

	
public class MyExceptionExample {

	public static void main(String[] a) {

		try {

			int i = 10 / 0;

		} catch (Exception ex) {

			System.out.println("Inside 1st catch Block");

		}

		try {

			int i = 10 / 10;

		} catch (Exception ex) {

			System.out.println("Inside 2nd catch Block");

		} finally {

			System.out.println("Inside 2nd finally block");

		}

	}

}
				

In the 1st try statement block we can see that we don't have finally block but in the 2nd try block we have finally block. So finally block is always optional.

	
 finally {

    System.out.println("Inside 2nd finally block");
  }
 		

2nd try block does not throw any exception but still after the execution of try block code executes finally statement block

	
 Output :
 Inside 1st catch Block
 Inside 2nd finally block

Tip 2 : Finally block is not executed in below two cases

  1. If following statement is included in the try block (Terminating code using system exit)
  2. System.exit(0);

  3. If the thread executing the try or catch code is interrupted or killed, the finally statement block may not execute.

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).

Why use java finally

  • Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Let's see the java finally example where exception occurs and handled.

  public class TestFinallyBlock {
	public static void main(String args[]) {
		try {
			int data = 25 / 0;
			System.out.println(data);
		} catch (ArithmeticException e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block is always executed");
		}
		System.out.println("rest of the code...");
	}
}

	
 Output: Exception in thread main java.lang.ArithmeticException:/ by zero
    finally block is always executed
   rest of the code... 
				

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).