目录

Throwable initCause(Throwable cause)

描述 (Description)

java.lang.Throwable.initCause()方法将此throwable的原因初始化为指定值。 (原因是throwable导致抛出此throwable。)它通常在构造函数内调用,或者在创建throwable之后立即调用

声明 (Declaration)

以下是java.lang.Throwable.initCause()方法的声明

public Throwable initCause(Throwable cause)

参数 (Parameters)

cause - 这是原因(保存以供以后通过getCause()方法检索)。 (允许空值,表示原因不存在或未知。)

返回值 (Return Value)

此方法返回对此Throwable实例的引用。

异常 (Exception)

  • IllegalArgumentException - 如果cause是可抛出的。

  • IllegalStateException - 如果此throwable是使用Throwable(Throwable)或Throwable(String,Throwable)创建的,或者此方法已在此throwable上调用。

例子 (Example)

以下示例显示了java.lang.Throwable.initCause()方法的用法。

package com.iowiki;
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....");
   }
} 

让我们编译并运行上面的程序,这将产生以下结果 -

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
↑回到顶部↑
WIKI教程 @2018