Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the getCause() method in Java?

Tarun Telang

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 example demonstrating the usage of getCause() method

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.

RELATED TAGS

java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring