finally block in Java [Guide]

In this post, we will learn about finally block in Java. We will see what is the syntax of the finally block, examples, when the finally block is not executed in Java, and best practices. Let's dive deep into the topic:

Read Also: Programs on Exception Handling in Java for Interview

What is finally

finally is a block of code that we can use with try block or try/catch block. Statements inside the finally block always execute regardless of the exception is caught or thrown.

Syntax of finally block

try {
   // Statements that can throw exception
}
catch(Exception e) {
   // Handling exception in catch block 
}
finally {
   // Statements to be executed 
}


Note: For each try block there can be zero or more catch blocks but only one finally block as shown in the below example.

Example of finally block

In the below example, you can see we are throwing ArithmeticException in the try block which has been handled in the catch block. Here, finally block will execute after the catch block.

public class FinallyExampleOne {
    public static void main(String args[]) {
      try {
          int num = 251/0;
          System.out.println("Inside try block");
      }
      catch(ArithmeticException e) {
          System.out.println("Number should not be divided by 0 (zero)");
      }
      /* finally block always execute even if the exception
      doesn't occur */
      finally {
          System.out.println("Inside finally block");
      }
      System.out.println("rest of the code ");
    }
}


Output:
Number should not be divided by 0 (zero)
Inside finally block
rest of the code


A finally block is more than just exception handling. You can put clean-up code in the finally block such as closing a file, closing connection or resource, etc.

return statement in try-catch and finally block in java

Let's see the below code. What do you think? Will finally block execute even if there is a return statement in the try block.

Note: finally block will be executed even when the try/catch block contains control transfer statements like return, break, continue.


public class FinallyExampleTwo {
    public static void main(String args[]) {
      int num = FinallyExampleTwo.getNumber();
      System.out.println("getNumber: "+ num);
    }
    
    public static int getNumber() {
      try {
          return 251;
      }
      /* finally block always execute even if the try block 
      contains the return statement */
      finally {
          System.out.println("Inside finally block");
      }
    }
}


Output:
Inside finally block
getNumber: 251

When finally block is not executed in Java?

According to Oracle docs,

1. The finally block may not execute if the JVM exits while the try or catch block code is being executed as shown below in the example.
2. Similarly, if the thread executing the try or catch block is killed or interrupted, then the finally block may not execute even then the application as a whole continues.

public class FinallyExampleThree {
    public static void main(String args[]) {
        try {
          System.out.println("Inside try block");
          System.exit(0);
        }
        catch(ArithmeticException e) {
          System.out.println("Number should not be divided by 0 (zero)");
        }
        finally {
          System.out.println("Inside finally block");
        }
      System.out.println("rest of the code ");
    }
}


Output:
Inside try block

System.exit(0) behaves differently than the return statement in the try block. Whenever System.exit(0) is called in try block then finally block does not execute.

More Examples of try/catch/finally block

Example 1: No Exception occurs in a try block


public class FinallyExampleFour {
    public static void main(String args[]) {
        try {
          System.out.println("Inside try block");
          int num = 150/5;
          System.out.println("Printing number : " + num);
        }
        catch(NullPointerException e) {
          System.out.println("NullPointerException");
        }
        finally {
          System.out.println("Inside finally block");
        }
      System.out.println("rest of the code ");
    }
}


Output:
Inside try block
Printing number : 30
Inside finally block
rest of the code

Example 2: Exception occurs in a try block but not handled in the catch block


public class FinallyExampleFive {
    public static void main(String args[]) {
        try {
          System.out.println("Inside try block");
          int num = 150/0;
          System.out.println("Printing number : " + num);
        }
        catch(NullPointerException e) {
          System.out.println("NullPointerException");
        }
        finally {
          System.out.println("Inside finally block");
        }
      System.out.println("rest of the code ");
    }
}


Output:
Inside try block
Inside finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyExampleFive.main(FinallyExampleFive.java:5)


Example 3: Exception occurs in a try block and handled in the catch block


public class FinallyExampleSix {
    public static void main(String args[]) {
        try {
          System.out.println("Inside try block");
          int num = 150/0;
          System.out.println("Printing number : " + num);
        }
        catch(ArithmeticException e) {
          System.out.println("ArithmeticException");
        }
        finally {
          System.out.println("Inside finally block");
        }
      System.out.println("rest of the code ");
    }
}


Output:
Inside try block
ArithmeticException
Inside finally block
rest of the code

That's all for today, please mention in the comments in case you have any questions related to finally block in java.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry