Java try catch finally

Summary: In this tutorial, you will learn how to use the Java try catch finally statement to effectively handle exceptions and make your program more robust.

Introduction to the Java try catch finally statement

The try catch statement has an optional finally block:

try {
    // Code that might throw an exception
} catch (Exception e) {
    // Handle the exception
} finally {
    // Cleanup code that always runs
}Code language: Java (java)

In this syntax:

  • The try block allows you to specify the code that you want to monitor for exceptions. If an exception occurs, the control flow jumps to the corresponding catch block.
  • The catch block allows you to handle specific types of exceptions that occur in the try block. Note that a try catch block may have multiple catch blocks to catch different exception types.
  • The finally block always executes regardless of whether an exception occurred or not. In other words, if the exception occurs the catch block, the finally block will execute. If an exception does not occur, the finally block will also execute.

In practice, you use the finally block to:

  • Clean up resources
  • Close files or database connections
  • Release the memory

Java try catch finally statement example

The following program reads a text file line by line and displays each line on the screen:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class App {
    public static void main(String[] args) {
        var fileName = "C:\\temp\\readme.txt";

        try {
            var fileReader = new FileReader(fileName);
            var bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            bufferedReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        }
    }
}
Code language: Java (java)

The problem with the program is that if the FileNotFoundException exception occurs, the following code will not execute:

bufferedReader.close();Code language: Java (java)

It means that the BufferedReader may not be closed properly, which may cause some issues like memory leaks.

To properly close the BufferedReader, you can use the finally block. For example:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class App {
    public static void main(String[] args) {
        var fileName = "C:\\temp\\readme.txt";

        BufferedReader bufferedReader = null;

        try {
            var fileReader = new FileReader(fileName);
            bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    }
}
Code language: Java (java)

In this example:

  • First, move the bufferedReader with the type BufferedReader out of the try block and initialize it to null. Otherwise, you will not be able to access it inside the finally block.
  • Second, call the close() method of the bufferedReader reference if it is not null.

However, the program will not compile because the close() method may cause IOException that needs to be handled explicitly:

bufferedReader.close();Code language: Java (java)

To fix it, you need to wrap the call of the close() method inside another try catch block:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class App {
    public static void main(String[] args) {
        var fileName = "C:\\temp\\readme.txt";

        BufferedReader bufferedReader = null;

        try {
            var fileReader = new FileReader(fileName);
            bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
}
Code language: Java (java)

Now it should work as expected.

Summary

  • Use the Java try catch finally statement to effectively handle exceptions in programs.
  • The finally block always executes regardless of whether an exception occurs.
  • Use the finally block to clean up resources, and close a file or database connection.