VOOZH about

URL: https://www.geeksforgeeks.org/java/throwable-getcause-method-in-java-with-examples/

⇱ Throwable getCause() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Throwable getCause() method in Java with Examples

Last Updated : 22 Jan, 2026

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()


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


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.
Comment