Java Finally Block Exception Handling Tutorial

In this section, we will learn what the `finally block` is and how it works in Java exception handling.

Prerequisite: handling exceptions via try catch blocks.

What is finally keyword in Java?

When working with databases or files or pretty much any external resources, usually we need to first establish a connection. After connecting to that external resource and having done the work, we need to release that external resource by closing the connection.

But in such programs that work with external resources, there are more risks that exceptions might happen!

So how do you make sure that no-matter if an exception occurs in a program or not, the connection will be closed before proceeding to other instructions?

This is where the `finally` block can help!

The `finally` block is a block of code that comes after a `try catch` blocks.

No-matter what the result of the instructions in the `try` block is, after the execution of the `try catch` blocks, the body of the `finally` block will run.

Note: When a `try` block is followed by a `finally` block, the use of `catch` block will be optional. Basically a `try` block needs to be followed by either one `catch` or one `finally` block. But of course we can use both of them if the design of a program requires both. In such case, the `finally` block will come after all the `catch` blocks.

Java finally block syntax:

try{

}catch(parameter){

}finally{

}

Example: using finally block in Java

import java.io.FileInputStream;
import java.io.IOException;

public class Simple {

    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("ssfsd");
        } catch ( IOException exception) {
            System.out.println(exception.getMessage());
        }finally {
            System.out.println("Inside the body of the finally block: ");
            if (fileInputStream !=null){
                try {
                    System.out.println("Closing the file");
                    fileInputStream.close();
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
    }
}

Output:

ssfsd (The system cannot find the file specified)

Inside the body of the finally block:

In this example, we’ve tried to access an external file via an object of type `FileInputStream` class.

If we succeed at connecting to a file, we need to close it at some point. For this reason, we used the `finally` block to close the file. Using the `finally` block ensures that no-matter if an exception occurs in the `try` block or everything proceed as expected, the instruction in this block is guaranteed to run.

In this example, because the address was pointing to a file that did not exist, we got an exception and it was handled in the `catch` block. But even after, the body of the `finally` block ran.

Using Java finally block without a catch Block

As mentioned before, we using a finally block, the catch block becomes optional and can be skipped.

Note that the `finally` block does not act as the handler of any sort of exception that might happen in the related `try` block! To handle these exceptions without any catch block, we have only one choice and that is to pass them to the enclosing scopes and they will be in charge of handling the exceptions.

Example: Java finally block without a catch block

package com.example.demo;

public class Main {

    public static void main(String[] args) {
        try {
            throwException();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static void throwException() throws Exception{
        try{
            throw new Exception("This is a simple exception");
        }finally {
            System.out.println("The body of the finally block will be run after the try block");
        }
    }
}

Output:

The body of the finally method will be run after the try block

This is a simple exception

Cases where finally block executes in Java:

The finally block runs at different situations and scenarios. Now let’s get deeper and examine these cases in details.

1- No Exception is thrown

When we have a try block, but no exception happens in that block, the finally block will run after the execution of the related `try` block finished.

Example: no-exception and finally block in Java

package com.example.demo;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the dontThrowException method");
            System.out.println(dontThrowException());
            System.out.println("After calling the dontThrowException method");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static String dontThrowException() throws Exception{
        try{
            System.out.println("The body of the try block in the dontThrowException method");
            return "This message is coming from the try block";
        }finally {
            System.out.println("The body of the finally block in the dontThrowException method");
        }
    }
}

Output:

Before calling the notThrowException method

The body of the try block in the notThrowException method

The body of the finally block in the notThrowException method

This message is coming from the try block

After calling the notThrowException method

2- Exception is thrown but not handled

If there’s an exception is thrown in the body of a try block and none of the catch handler of that try block could handle the exception, before moving back to the caller method, the finally block will run first and then the execution engine moves back to the caller method. (Note that the exception won’t be handled in the body of the finally block and it will be passed to the caller method as well).

Example: Java finally block and not handled exception

package com.example.demo;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the throwException method");
            throwException();
            System.out.println("After calling teh throwException method");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static void throwException() throws Exception{
        try{
            System.out.println("The body of the try block in the throwException method");
            throw new Exception("This is a not handled exception");
        }catch(IOException io){
            System.out.println(io.getMessage());
        }
        finally {
            System.out.println("The body of the finally block in the throwException method");
        }
    }
}

Output:

Before calling the throwException method

The body of the try block in the throwException method

The body of the finally block in the throwException method

This is a not handled exception

3- Exception is thrown and handled perfectly

When an exception happens in a try block and it is handled correctly in one of the catch blocks of that try block, the finally block will run after the catch block that handled the error.

Example: Java finally block and handled exception

package com.example.demo;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the throwException method");
            throwException();
            System.out.println("After calling teh throwException method");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static void throwException(){
        try{
            System.out.println("The body of the try block in the throwException method");
            throw new Exception("This is a not handled exception");
        }catch(Exception io){
            System.out.println("The body of the catch block in the throwException method");
            System.out.println(io.getMessage());
        }
        finally {
            System.out.println("The body of the finally block in the throwException method");
        }
    }
}

Output:

Before calling the throwException method

The body of the try block in the throwException method

The body of the catch block in the throwException method

This is a not handled exception

The body of the finally block in the throwException method

After calling the throwException method

4- Method returns from try block

When there’s a call to the return statement in the body of the try block, before that return statement terminates the work of the target method, the finally block will run first and then the return statement executes.

Example: Java finally block and the `return` statement in try block

package com.example.demo;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the throwException method");
            System.out.println(throwException());;
            System.out.println("After calling teh throwException method");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static String throwException(){
        try{
            System.out.println("The body of the try block in the throwException method");
            return "Returning from the try block in the throwException method";
        }catch(Exception e){
            System.out.println("The body of the catch block in the throwException method");
            System.out.println(e.getMessage());
        }
        finally {
            System.out.println("The body of the finally block in the throwException method");

        }
        return "Hello";
    }
}

Output:

Before calling the throwException method

The body of the try block in the throwException method

The body of the finally block in the throwException method

Returning from the try block in the throwException method

After calling the throwException method

5- Method returns from catch block

No matter where we call the return statement (try block or catch block) the finally block will run first and then comes the return statement.

Example: Java finally block and the `return` statement from catch block

package com.example.demo;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the throwException method");
            System.out.println(throwException());;
            System.out.println("After calling teh throwException method");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static String throwException(){
        try{
            System.out.println("The body of the try block in the throwException method");
            throw new Exception("This is a simple exception");
        }catch(Exception e){
            System.out.println("The body of the catch block in the throwException method");
            System.out.println(e.getMessage());
            return "Returning from the catch block in the throwException method";
        }
        finally {
            System.out.println("The body of the finally block in the throwException method");
        }
    }
}

Output:

Before calling the throwException method

The body of the try block in the throwException method

The body of the catch block in the throwException method

This is a simple exception

The body of the finally block in the throwException method

Returning from the catch block in the throwException method

After calling the throwException method

Java Finally block and `System.exit()` method

There’s only one case where the finally block will not be executed! This case is when we call the System.exit() method!

System.exit() will terminate the work of the entire program and not just a method! And for that reason, calling this method won’t allow the execution of a finally block.

Example: Using System.exit() method to prevent finally block execution in Java

package com.example.demo;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the throwException method");
            throwException();
            System.out.println("This message won't be printed on the output");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static void throwException() throws Exception{
        try{
            System.exit(0);
        }finally {
            System.out.println("The body of the finally block won't run");
        }
    }
}

Output:

Before calling the throwException method.

Using return statement in Java finally block

One important note to remember is that if there’s a return statement within the body of a finally block, and there’s another return statement within the body of the related try block, the one in the finally block will override the other return statements! As mentioned before, when there’s return statement in a try block, first the finally block will run and then the call to the return statement will continue.

Now consider there’s a return statement in the finally block as well! In that case, the execution engine will run that statement and terminate the target method without backing to the return statement that was in the try block.

Example: return statement in Java finally block

package com.example.demo;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("Before calling the throwException method");
            System.out.println(throwException());
            System.out.println("After calling the throwException method");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static String throwException() throws Exception{
        try{
            return "This message is coming from the try block";
        }finally {
            return "This message is coming from the finally block";
        }
    }
}

Output:

Before calling the throwException method

This message is coming from the finally block

After calling the throwException method
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies