Home » Java » finally block in java

finally block in java

Java finally block is always executed whether exception is handled or not.Java finally block must be followed by try or catch block.

The main usage of finally block is to releases the resources which are obtained in try block (resources are opening files, opening databases connection etc.).

Java finally block must be followed by try or catch block.


Example


    public static void main(String[] args){
        FileReader fileInput = null;
        
        try
        {
           //Open the input file
           fileInput = new FileReader("Untitled.txt");
        }
        catch(FileNotFoundException | IOException ex)
        {
            //handle both exceptions
        }
        finally 
        {
            //We must remember to close streams
            //Check to see if they are null in case there was an
            //IO error and they are never initialised
            if (fileInput != null)
            {
                fileInput.close();
            }
        }
    }
 

Example code of finally block


package com.jwt.java;

public class ExceptionExample {
	public static void main(String[] a) {
		/**
		 * Exception will occur and it will caught in catch block and contol
		 * will goto finally block.
		 */
		try {
			int i = 10 / 0;
		} catch (Exception ex) {
			System.out.println("Inside 1st catch Block");
		} finally {
			System.out.println("Inside 1st finally block");
		}
		/**
		 * In this case exception will not occur, after executing try block the
		 * contol will goto finally block.
		 */
		try {
			int i = 10 / 10;
		} catch (Exception ex) {
			System.out.println("Inside 2nd catch Block");
		} finally {
			System.out.println("Inside 2nd finally block");
		}
	}
}

Output :

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


Previous Next Article

comments powered by Disqus