chained exception in java and java chained exceptions

Chained Exceptions in Java

Chained exceptions let you connect one exception to another so you can show that one problem triggered the next. This relationship makes the root cause easier to spot and helps you troubleshoot more effectively. Java enables chained exceptions through specific constructors and methods on the Throwable class.

Throwable Constructors and Methods for Chaining

Constructors

  • Throwable(Throwable cause) — records the underlying cause that led to the current exception.
  • Throwable(String msg, Throwable cause) — lets you attach a descriptive message for extra clarity along with the originating cause.

Methods

  • getCause() — retrieves the actual cause behind an exception.
  • initCause(Throwable cause) — assigns a cause to the exception that is currently being handled.

Example Scenario

Imagine code that throws an ArithmeticException when it tries to divide by zero, even though the real underlying issue is a number format problem. On its own, the method reports only the ArithmeticException, so the user never learns the true reason. Chained exceptions solve this by linking the actual cause to the thrown exception.

public class ChainedException {
    public static void main(String[] args) {
        int a = 0, b;
        try {
            b = 4 / a;
        } catch (ArithmeticException e) {
            if (a <= 0) {
                // Set the actual cause of the exception
                e.initCause(new NumberFormatException("This is actual cause of the exception"));
            }
            // Retrieve the actual cause
            System.out.println(e.getCause());
            throw e;
        }
    }
}

Output: java.lang.NumberFormatException: This is actual cause of the exception, followed by the ArithmeticException stack trace and a "Caused by" section pointing to the NumberFormatException.

Continue Learning

Explore more about handling exceptions and related JavaGoal resources.

Exception Handling in Java JavaGoal Home Leave a Comment