Java.lang.Throwable.initCause() 方法
描述
java.lang.Throwable.initCause() 方法将此 throwable 的原因初始化为指定值。 (原因是导致这个 throwable 被抛出的 throwable。)它通常在构造函数中调用,或者在创建 throwable 之后立即调用
声明
以下是 java.lang.Throwable.initCause() 方法的声明。
public Throwable initCause(Throwable cause)
参数
cause − 这就是原因(它被保存以供以后通过 getCause() 方法检索)。 (允许使用空值,表示原因不存在或未知。)
返回值
此方法返回对此 Throwable 实例的引用。
异常
IllegalArgumentException − 如果原因是可抛出的。
IllegalStateException − 如果这个 throwable 是用 Throwable(Throwable) 或 Throwable(String,Throwable) 创建的,或者这个方法已经在这个 throwable 上调用过。
示例
下面的例子展示了 java.lang.Throwable.initCause() 方法的使用。
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....");
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
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

