The getCause() method of the Throwable class is used to retrieve the original cause of an exception. If no cause is associated with the exception, it returns null.
- It is mainly used in exception chaining to identify the root cause of an error.
- Methods like printStackTrace() internally use getCause() to display nested exception details.
Example 1: Exception Chaining with initCause()
class GFG {
public static void main(String[] args) {
try {
divide(2, 0);
} catch (ArithmeticException e) {
System.out.println("Cause of Exception: " + e.getCause());
}
}
public static void divide(int a, int b) throws Exception {
try {
int result = a / b;
} catch (ArithmeticException e) {
// Creating a new exception and setting the cause
ArithmeticException newEx = new ArithmeticException("Division failed");
newEx.initCause(e);
throw newEx;
}
}
}
Output
Cause of Exception: java.lang.ArithmeticException: / by zero
Explanation:
- The original ArithmeticException caused by division by zero is set as the cause of a new ArithmeticException.
- Calling getCause() retrieves the original exception.
Syntax
public Throwable getCause()
Return Value: Returns the Throwable that caused this exception, or null if the cause is unknown.Class:
How getCause() Works
- When an exception is created, it can optionally reference another exception as its cause.
- The cause can be set during construction or later using the initCause(Throwable cause) method.
- Calling getCause() on an exception returns the underlying cause.
Example 2: Without Exception Chaining
class GFG {
public static void main(String[] args) {
try {
divide(2, 0);
} catch (ArithmeticException e) {
System.out.println("Cause of Exception: " + e.getCause());
}
}
public static void divide(int a, int b) throws Exception {
int result = a / b; // Throws ArithmeticException directly
}
}
Output
Cause of Exception : null
Explanation: Here, no cause was explicitly set, so getCause() returns null.
Key Points:
- getCause() helps debug chained exceptions by identifying the root cause.
- Use initCause(Throwable cause) to link exceptions manually.
- Always check for null to avoid NullPointerException.