Throwable getCause() method in Java with Examples
Last Updated :
12 Apr, 2023
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
import java.io.*;
class GFG {
public static void main(String[] args)
throws Exception
{
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 i = a / b;
}
catch (ArithmeticException e) {
ArithmeticException exe = new ArithmeticException();
exe.initCause(e);
throw (exe);
}
}
}
|
Output:
Cause of Exception: java.lang.ArithmeticException: / by zero
Example 2:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
throws Exception
{
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 i = a / b;
}
}
|
Output:
Cause of Exception : null
References: https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getCause()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...