1.

Get the cause of an exception in Java

Answer»

In Java, we use the getCause() method which returns the cause of the exception or returns null if the cause of the exception is not known.

The declaration of the java.lang.THROWABLE.getCause() is

public Throwable getCause()

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 FORMATION of the initCause(Throwable) method.

Let us see an example on the working of the getCause() method as we try to compile a program with ArrayIndexOutOfBoundsException:

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

The output is as follows:

$JAVAC Example.java $java Example Cause = java.lang.ArrayIndexOutOfBoundsException: 8


Discussion

No Comment Found