java.lang.Throwable.initCause()%uA0方法初始化该throwable为指定值的原因。 (原因是导致此抛出得到抛出的对象。)
它一般被调用在构造函数中,或者创建抛出后
声明
以下是java.lang.Throwable.initCause()方法的声明
public Throwable initCause(Throwable cause)
参数
-
cause%uA0--%uA0这个是原因(保存为通过getCause()方法之后的检索)。 (一允许null值,指出原因是不存在的或未知的。
返回值
该方法返回一个引用该Throwable实例。
异常
-
IllegalArgumentException%uA0-- 如果原因是可抛出的。
-
IllegalStateException%uA0--如果抛出用Throwable(Throwable)或Throwable(String,Throwable)创建,或者这种方法已经调用该抛出。
例子
下面的例子显示java.lang.Throwable.initCause()方法的使用。
package com.yiibai 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