Overview

In Java, we are provided with the “finally” block, which we may use to place important code snippets, for example, clean-up code, code for closing a file, code for closing a network connection, etc.

The code in the finally block runs regardless of whether or not an exception arises whether or not a thrown exception is handled, etc. Following are the three common practical use cases of the final block in Java:

When no exception arises

The program, in this case, executes properly and does not raise any exceptions. After the try block has completed running, the finally block starts running. Let us have a look at the code snippet below to gain a better understanding:

import java.io.*;
 
class myClass{
    public static void main(String[] args){
        try{
            System.out.println("Hi, from try block!");
            System.out.println(345/5);
        }
        catch (ArithmeticException e) {  
            System.out.println("An arithmetic error found!");           
        }
        finally{
            System.out.println('Hi, from finally!");
        }
    }
}

Output

Hi, from try block!
69
Hi, from finally!

write your code here: Coding Playground

An exception is thrown and handled

The program, in this case, raises an exception which is later handled by a catch block. Lastly, once the catch block has completed running, the finally block executes.

import java.io.*;
class myClass{
    public static void main(String[] args){
        try{
            System.out.println("Hi, from the try block!");
            System.out.println(345 / 0);
        }
        catch(ArithmeticException e){
            System.out.println("Hi, from catch block!");
        }
        finally{
          System.out.println("Hi, from the finally block!");
        }
    }
}

Output

Hi, from the try block!
Hi, from catch block!
Hi, from the finally block!

write your code here: Coding Playground

When an exception is thrown and not handled by any catch block

The program, in this case, throws an exception that is not handled by any catch block. Hence, after the try block has finished executing, the finally block starts running. Once the finally block completes executing, our program ends abnormally. Although, the finally block will have run just fine.

import java.io.*;
class GFG {
    public static void main(String[] args){
        try{
            System.out.print("Hi, from the try block!\n");
            System.out.println(345 / 0);
        }
        catch(NullPointerException e){
            System.out.println("Hi, from the catch block!");
        }
        finally{
            System.out.print("Hi, from the finally block!\n");
        }
        System.out.println("Hi, from no bock!");
    }
}

Output

Hi, from the try block!
Hi, from the finally block!
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GFG.main(GFG.java:6)

write your code here: Coding Playground