Importance of the getCause() method in Java?\n


The getCause() method is from Throwable class and we can use this method which returns the cause of the exception or returns null if the cause of the exception is not known. The getCause() method doesn’t accept any arguments and doesn’t throw an exception. It returns the cause that was provided by one of its constructors or that was determined by the formation of the initCause() method of Throwable class.

Syntax

public Throwable getCause()

Example

public class GetCauseMethodTest {
   public static void main(String[] args) throws Exception {
      try {
         myException();
      } catch(Exception e) {
         System.out.println("Cause = " + e.getCause());
      }
   }
   public static void myException() throws Exception {
      int arr[] = {1, 3, 5};
      try {
         System.out.println(arr[8]);
      } catch(ArrayIndexOutOfBoundsException aiobe) {
         Exception e = new Exception();
         throw(Exception); // throwing the exception to be caught by catch block in main()
         e.initCause(aiobe); // supplies the cause to getCause()
      }
   }
}

Output

Cause = java.lang.ArrayIndexOutOfBoundsException: 8

Updated on: 03-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements