Java Rethrow Exception

Summary: in this tutorial, you’ll learn how to rethrow an exception in Java using the throw statement.

The try catch statement allows you to catch an exception in the try block and handle it appropriately in the catch block.

Sometimes, you may not be able to handle an exception that is caught by a catch block. In this case, you can log the error message before propagating the exception to the call stack.

This technique is called rethrowing an exception, meaning that you re-throw the exception that has been caught by the catch block.

By rethrowing the exception, you can perform an action like logging the error message before notifying a higher-level method that the exception has occurred.

To rethrow an exception, you use the throw statement inside the catch block like this:

try{
   // code that causes an exception
} catch(ExceptionType e) {
   // log the information
   throw e; 
}Code language: Java (java)

Note that you can rethrow the same exception that occurs in the try block or throw a new exception.

Rethrowing an exception example

The following example illustrates how to rethrow an exception:

public class App {
    public static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            // write to a log
            System.err.println("Division by zero exception occurred.");

            // rethrow the same exception
            throw e;
        }
    }

    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.err.println(e.getMessage());
        }
    }
}Code language: Java (java)

How it works.

First, define the divide() method that takes two integers as parameters and returns the result of dividing the first parameter by the second one.

The divide() method catches the ArithmeticException that occurs when dividing by zero. In the catch() block, the divide() method first writes an error message to the standard error stream and rethrows the same exception.

It means that the exception will be propagated up the call stack and may be caught by an exception handler in a higher-level method.

Second, in the main() method, call the divide() method in a try block and use a catch block to catch the ArithmeticException that was rethrown by the divide() method.

Summary

  • Use the throw statement in the catch block to rethrow an exception so that it can be propagated to the higher-level method.