Thursday, September 4, 2025
HomeLanguagesJavaThrowable getCause() method in Java with Examples

Throwable getCause() method in Java with Examples

The getCause() method of Throwable class is the inbuilt method used to return the cause of this throwable or null if cause can’t be determined for the Exception occurred. This method help to get the cause that was supplied by one of the constructors or that was set after creation with the initCause(Throwable) method. All the PrintStackTrace methods of Throwable class invoke getCause() method to determine the cause of the Throwable or Exception. In simple terms, it can be said that this method returns the cause because of which Exception occurred. Syntax:

public Throwable getCause()

Return Value: This method returns the cause of this Throwable or null if cause can’t be determined. Below programs demonstrate the getCause() method of Throwable Class: Example 1: 

Java




// Java program to demonstrate
// the getCause() Method.
 
import java.io.*;
 
class GFG {
 
    // Main Method
    public static void main(String[] args)
        throws Exception
    {
 
        try {
 
            // divide the numbers
            divide(2, 0);
        }
 
        catch (ArithmeticException e) {
 
            System.out.println("Cause of Exception: "
                               + e.getCause());
        }
    }
 
    // method which divides two number
    public static void divide(int a, int b)
        throws Exception
    {
 
        try {
 
            // divide two numbers
            int i = a / b;
        }
 
        catch (ArithmeticException e) {
 
            // initializing new Exception with cause
            ArithmeticException exe = new ArithmeticException();
 
            exe.initCause(e);
 
            throw(exe);
        }
    }
}


Output:

Cause of Exception: java.lang.ArithmeticException: / by zero

Example 2: 

Java




// Java program to demonstrate
// the getCause() Method.
 
import java.io.*;
 
class GFG {
 
    // Main Method
    public static void main(String[] args)
        throws Exception
    {
 
        try {
 
            // divide the numbers
            divide(2, 0);
        }
 
        catch (ArithmeticException e) {
 
            System.out.println("Cause of Exception : "
                               + e.getCause());
        }
    }
 
    // method which divides two number
    public static void divide(int a, int b)
        throws Exception
    {
 
        // divide two numbers
        int i = a / b;
    }
}


Output:

Cause of Exception : null

References: https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getCause()

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS