finally Keyword in Java With Examples

The finally keyword

The keyword used to represent the block associated with affirmative execution regardless of any exception has occurred or not. Several important processes need to be performed mandatorily before the execution of the program completes with or without exception. Such processes include closing file, close a JDBC connection, clearing the objects, closing the scanner, etc. As a result of such a block declaration, the statements enclosed will be executed certainly. The general syntax of the finally block is as follows:

try{
//Fishy Code
}
catch(ExceptionType1 obj){
//Handler for ExceptionType1
}
finally{
//This part of code will always be executed.
}

In our previous lecture, we found try always accompanied by one or more catch blocks. But in Java, we can completely omit the catch block if we have finally with a try.

try{
//Fishy Code
}
finally{
//This part of code will always be executed.
}

The finally block is executed by the JVM before completing the program execution.

Let us dive into a variety of scenarios to see the impact of the finally block.

1. No Exception Occurred

public class MyExceptionFinally{
     public static void main(String []args){
        System.out.println("I am after try-catch-finally block");
        try{
            System.out.println("I am inside try block !!!");
            int x=54;
            int y=9;
            float z=x/y;
            System.out.println("I print fraction inside try block. i.e frac = "+z);
        }
        catch(ArithmeticException obj){
            System.out.println("I am inside handler of ArithmeticException");
        }
        finally{
            System.out.println("I am inside finally block !!!");
        }
        System.out.println("I am after try-catch-finally block");
     }
}

Output:

I am after try-catch-finally block
I am inside try block !!!
I print fraction inside try block. i.e frac = 6.0
I am inside finally block !!!
I am after try-catch-finally block

2. Exception Occurred

public class MyExceptionFinally{
     public static void main(String []args){
        System.out.println("I am after try-catch-finally block");
        try{
            System.out.println("I am inside try block !!!");
            int x=54;
            int y=0;
            float z=x/y;
            System.out.println("I print fraction inside try block. i.e frac = "+z);
        }
        catch(ArithmeticException obj){
            System.out.println("I am inside handler of ArithmeticException");
        }
        finally{
            System.out.println("I am inside finally block !!!");
        }
        System.out.println("I am after try-catch-finally block");
     }
}

Output:

I am after try-catch-finally block
I am inside try block !!!
I am inside handler of ArithmeticException
I am inside finally block !!!
I am after try-catch-finally block

So we can see that finally block is always executed and is independent of an exception to occur.

Even if we encounter a return statement in a try block, the control goes to finally block before leaving the current method irrespective of the occurrence of an exception. Let us look at a few examples.

3. Return statement inside try without exception

public class MyExceptionFinally{
     public static void main(String []args){
        float result = getFrac(54,2);
        System.out.println("I print fraction inside main method. i.e frac = "+result);
     }

     public static float getFrac(int x,int y){
        System.out.println("I am after try-catch-finally block");
        try{
            System.out.println("I am inside try block !!!");
            float z=x/y;
            return z;
        }
        catch(ArithmeticException obj){
            System.out.println("I am inside handler of ArithmeticException");
        }
        finally{
            System.out.println("I am inside finally block !!!");
        }
        System.out.println("I am after try-catch-finally block");
        return 0;
     }
}

Output:

I am after try-catch-finally block
I am inside try block !!!
I am inside finally block !!!
I print fraction inside main method. i.e frac = 27.0

4. Return statement inside try without exception

public class MyExceptionFinally{
     public static void main(String []args){
        float result = getFrac(54,0);
        System.out.println("I print fraction inside main method. i.e frac = "+result);
     }

     public static float getFrac(int x,int y){
        System.out.println("I am after try-catch-finally block");
        try{
            System.out.println("I am inside try block !!!");
            float z=x/y;
            return z;
        }
        catch(ArithmeticException obj){
            System.out.println("I am inside handler of ArithmeticException");
        }
        finally{
            System.out.println("I am inside finally block !!!");
        }
        System.out.println("I am after try-catch-finally block");
        return 0;
     }
}

Output:

I am after try-catch-finally block
I am inside try block !!!
I am inside handler of ArithmeticException
I am inside finally block !!!
I am after try-catch-finally block
I print fraction inside main method. i.e frac = 0.0

Difference between similar words (final, finally, finalize)

final: This restricts any change/derivation to the entity. A variable defined as final can’t be changed once assigned a value. A final method cannot be overridden, and the final class cannot be a parent to any class and makes every method of it to be final.

finally: This keyword is a part of exception-handling. The block defined as finally is certain to be executed regardless of any exception to occur/caught/handled.

finalize: It is a method of class Object which is called by the garbage collector on an object to confirm that no more references to the object exist in the memory. All the subclasses implicitly override this method for cleanup purposes and dispose of all the resources used during the execution.

This was all about finally block. We will discuss creating a Custom Exception in the next lecture.