Saturday, November 16, 2024
Google search engine
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

Recent Comments