Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – The finally block

The finally block is similar to try block, but it is always associated with try-catch block or try block alone.

The finally block cannot be used alone.

But try block or try-catch block can be used without finally block.

The finally block gets execute either exception is thrown by try block or not.

Generally, it is used to perform an important task or to close the resources that are opened, so that resources can be closed definitely either exception occurs or not in the try block.

The finally block can be used only one time, unlike multiple catch clauses.

Example – I

import java.util.Scanner;

class FinallyDemo 
{
    public static void main(String args[])
    {
        System.out.println("Enter any number :: ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        try
        {
            int i = 10/num;
            System.out.println("i = "+i);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception Handled");
        }
        finally
        {
            System.out.println("Inside finally block");
        }
    }
}

If number entered is zero

Output

Enter any number ::
0
Arithmetic Exception Handled
Inside finally block

If number entered is other than zero

Output

Enter any number ::
5
i = 2
Inside finally block

Example – II

class FinallyDemo2 
{
    public static void trial()
    {
        try
        {
            return;
        }
        finally
        {
            System.out.println("Inside finally block");
        }
    }
		
    public static void main(String args[]) 
    {
        trial();
    }
}

Output

Inside finally block

Note

The try block must be followed by catch block or finally clause.

 

Leave a reply