What is the getCause() method in Java?

Introduction

The getCause() method of the Throwable class is used to retrieve the cause of a throwable, if any. This method is generally used to find the root cause of an error. If there are multiple causes for the error or exception, this method returns the innermost cause.

Syntax

The declaration for the java.lang.Throwable.getCause() method is:

public final Throwable getCause()
Declaration for java.lang.Throwable.getCause() method

Parameters

This method does not take any parameters.

Return value

The cause of this throwable or null if the cause is nonexistent or unknown.

Exceptions

This method does not throw any exception.

Code example

Let's look at a code example that demonstrates how a cause is set for the throwable and retrieved, using the getCause() method.

class GetCauseDemo {
public static void main(String args[]){
try {
int a[] = new int[5];
a[-1] = 1;
} catch (Exception e){
Throwable t = new Throwable(" caused by access to invalid array length ",e);
// printing the cause
System.out.println("Cause is: "+t.getCause());
}
}
}

Code explanation

In the code above, an exception is caused by accessing an invalid array length. The exception is then wrapped in a throwable and the cause of that throwable is printed using the getCause() method.

This will produce the following result:

Cause is: java.lang.ArrayIndexOutOfBoundsException: -1
Code output

Conclusion

In this post, we saw the getCause() method of Java. This method is generally used to find the root cause of an error. The method takes no parameters and does not throw any exception. The return type of this method is a Throwable object that may be null if the cause is non-existent or unknown.

Free Resources