Java try catch

Summary: In this tutorial, you will learn how to use the Java try catch statement to handle exceptions effectively.

Introduction to Java try catch statement

In Java, an exception is an error that occurs at runtime. If you don’t handle the exception properly, the program will crash.

For example, the following program attempts to divide an integer by zero:

public class App {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int result = a / b; // exception
        System.out.println(result);
    }
}Code language: Java (java)

If you run the program, line 5 will throw an exception with the following error message:

Exception in thread "main" java.lang.ArithmeticException: / by zeroCode language: plaintext (plaintext)

The error message indicates the "/ by zero" (division by zero) exception occurred.

When the division by zero exception occurred, the program terminated immediately. In other words, the program stopped and didn’t execute any other statements after line 5.

Also, you see the following class in the error message:

java.lang.ArithmeticExceptionCode language: CSS (css)

In Java, all exceptions are represented by classes. In this example, the ArithmeticException class represents the division by zero exception.

To prevent the program from crashing when an exception occurs, you need to handle it using the try catch statement.

The goals of exception handling are to recover from the error and perform additional actions such as:

  • Displaying a user-friendly message and requesting users to take corrective actions to keep the program running.
  • Logging error messages to a log file so that you as a developer can address them later.
  • Cleaning up resources like closing a file or shutting down a network connection.

Here’s the basic syntax of the try catch statement:

try {
    // code that may throw an exception
} catch(ExceptionType e) {
    // handle an exception
}Code language: Java (java)

In this syntax:

  • The try block contains the code that may cause an exception.
  • The catch block contains the code that handles the exception.

When an exception occurs, the program skips the remaining code in the try block and jumps to the catch block immediately.

The following example shows how to use the try catch statement to handle the exception:

public class App {
    public static void main(String[] args) {
        int a = 10, b = 0;
        int result;

        try {
            result = a / b; // exception
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}Code language: Java (java)

In this example, we place the code that causes an exception in the try block:

result = a / b;

When the program encounters the division by zero exception, it doesn’t crash midway.

Instead, the program gracefully handles the exception by jumping to the catch block and displaying an error message.

Because of the try catch statement, the program can continue running to the end without any interruptions.

Understanding Java exception types

All exceptions are represented by classes that are the subclasses of the Throwable class. All exception classes form a class hierarchy.

The following picture illustrates the exception class hierarchy:

The Throwable is the root of the exception hierarchy. Like a regular class, it is a subclass of the Object class. All exception classes are the subclasses of the Throwable class.

In practice, you don’t work with the Throwable class directly. Instead, you’ll work with the subclasses of the Throwable class such as Exception class.

Java try catch with multiple catch blocks

The try catch statement may include multiple catch blocks where each catch block catch and handle a specific exception type.

Here’s the syntax of the try catch statement with multiple catch blocks:

try {
    // Code that may throw an exception
} catch (ExceptionType1 e1) {
    // Handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle ExceptionType2
} catch (ExceptionType3 e3) {
    // Handle ExceptionType3
}Code language: Java (java)

When an exception occurs, Java searches for a matching exception type in the catch blocks sequentially from top to bottom.

Once Java finds a catch block whose exception type matches the thrown exception, it executes that specific catch block and skip the remaining catch blocks.

This means that you should place the most specific exception type higher and the more generic exception type lower in the catch block list.

For example, reading a file may cause multiple exceptions:

  • The file may not exist (FileNotFoundException)
  • Error while reading a file (IOException)
  • And other unexpected errors (Exception)

To handle each exception properly, you need to use a try with multiple catch blocks. Each catch block handles a specific type of exception accordingly.

The following example illustrates how to read a file and handle the exceptions using multiple catch blocks:

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) {
        String 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)

Catching multiple exceptions using a single catch block

If you handle multiple exception types using the same logic, you’ll have duplicate code:

try {
    // code that may throw an exception
} catch (ExceptionType1 e1) {
    // handle exception
} catch (Exceptiontype2 e2) { 
    // handle exception (same as ExceptionType1)
}Code language: Java (java)

To remove the duplicate code, Java SE 7 and later allows you to catch more than one type of exception within one catch block like this

try {
  // code that may throw an exception
} catch (ExceptionType1 | Exceptiontype2 e) { 
  // handle exception
}Code language: Java (java)

In this syntax, you can place the code that handles exception types ExceptionType1 and ExceptionType2 once in a single catch block.

Summary

  • Exceptions are errors that occur at run time.
  • Exceptions are represented by classes, which are the subclasses of the Throwable class.
  • Use Java try catch statement to handle the exceptions.