Java.lang.Throwable.initCause() Method



Description

The java.lang.Throwable.initCause() method initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.) It is generally called from within the constructor, or immediately after creating the throwable

Declaration

Following is the declaration for java.lang.Throwable.initCause() method

public Throwable initCause(Throwable cause)

Parameters

cause − This is the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

Return Value

This method returns a reference to this Throwable instance.

Exception

  • IllegalArgumentException − if cause is this throwable.

  • IllegalStateException − if this throwable was created with Throwable(Throwable) or Throwable(String,Throwable), or this method has already been called on this throwable.

Example

The following example shows the usage of java.lang.Throwable.initCause() method.

package com.tutorialspoint;

import java.lang.*;

public class ThrowableDemo {

   public static void main(String[] args) throws Throwable {
     try {
         Exception1();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
  
   public static void Exception1()throws amitException{
      try {
         Exception2();
      } catch(otherException e) {
         amitException a1 = new amitException();
     
         // initializes the cause of this throwable to the specified value. 
         a1.initCause(e);
         throw a1;
      }
   }
  
   public static void Exception2() throws otherException {
      throw new otherException();
   }
}

class amitException extends Throwable {
   amitException() {
      super("This is my Exception....");
   }
}

class otherException extends Throwable {
   otherException() {
      super("This is any other Exception....");
   }
} 

Let us compile and run the above program, this will produce the following result −

Exception in thread "main" amitException: This is my Exception....
        at ThrowableDemo.Exception1(ThrowableDemo.java:18)
        at ThrowableDemo.main(ThrowableDemo.java:6)
Caused by: otherException: This is any other Exception....
        at ThrowableDemo.Exception2(ThrowableDemo.java:27)
        at ThrowableDemo.Exception1(ThrowableDemo.java:15)
        ... 1 more
java_lang_throwable.htm
Advertisements