Last Updated : 06 Aug, 2025
Chained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception.
Example: The following example demonstrates how to use chained exceptions in Java.
Java
// Working of chained exceptions
public class Geeks {
public static void main(String[] args) {
try {
// Creating an exception
NumberFormatException ex = new NumberFormatException("Primary Exception");
// Setting the cause of the exception
ex.initCause(new NullPointerException("Root cause of the exception"));
// Throwing the exception with a cause
throw ex;
}
catch (NumberFormatException ex) {
// Displaying the primary exception
System.out.println("Caught Exception: " + ex);
// Displaying the root cause of the exception
System.out.println("Cause of Exception: " + ex.getCause());
}
}
}
Caught Exception: java.lang.NumberFormatException: Primary Exception Cause of Exception: java.lang.NullPointerException: Root cause of the exception
Note: Chained exceptions, also known as nested exceptions, allow us to associate a cause with an exception in Java. This is useful when we want to propagate information about the original cause of an exception.
ConstructorsExample: Using a Custom Message with Chained Exceptions
In Java, we can chain exceptions using the constructor of the Throwable class.
Java
// Use a custom message with chained exception
public class Geeks {
public static void main(String[] args) {
try {
// Code that might throw an exception
int[] n = new int[5];
int divisor = 0;
for (int i = 0; i < n.length; i++) {
int res = n[i] / divisor;
System.out.println(res);
}
}
catch (ArithmeticException e) {
// Creating a new exception with
// the original as the cause
throw new RuntimeException
("Error: Division by zero occurred", e);
}
}
}
Output:
Explanation: In this example, an array of integers and sets the divisor to 0.
Advantages of Chained Exceptions:
The advantages of chained exceptions are listed below:
Disadvantages of Chained Exceptions:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4