Throwable类的initCause()方法用于初始化此Throwable的原因,并将指定的原因作为参数传递给initCause()。实际上,原因是引发异常时导致抛出此对象的可抛出对象。此方法只能调用一次。通常,从构造函数内部或在创建throwable之后立即调用此方法。如果调用Throwable是使用Throwable(Throwable)或Throwable(String,Throwable)创建的,则即使调用一次此方法也不能。
用法:
public Throwable initCause?(Throwable cause)
参数:此方法接受cause作为表示此Throwable原因的参数。
返回值:此方法返回对此Throwable实例的引用。
异常:该方法抛出:
IllegalArgumentException如果原因是可抛出的。
IllegalStateException如果此Throwable是使用Throwable(Throwable)或Throwable(String,Throwable)创建的,或者已经在此throwable上调用了此方法。
以下程序说明了Throwable类的initCause方法:
示例1:
// Java program to demonstrate
// the initCause() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
testException1();
}
catch (Throwable e) {
System.out.println("Cause : "
+ e.getCause());
}
}
// method which throws Exception
public static void testException1()
throws Exception
{
// ArrayIndexOutOfBoundsException Exception
// This exception will be used as a Cause
// of another exception
ArrayIndexOutOfBoundsException
ae
= new ArrayIndexOutOfBoundsException();
// create a new Exception
Exception ioe = new Exception();
// initialize the cause and throw Exception
ioe.initCause(ae);
throw ioe;
}
}
输出:
Cause : java.lang.ArrayIndexOutOfBoundsException
示例2:
// Java program to demonstrate
// the initCause() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
// add the numbers
addPositiveNumbers(2, -1);
}
catch (Throwable e) {
System.out.println("Cause : "
+ e.getCause());
}
}
// method which adds two positive number
public static void addPositiveNumbers(int a, int b)
throws Exception
{
// if Numbers are Positive
// than add or throw Exception
if (a < 0 || b < 0) {
// create a Exception
// when Numbers are not Positive
// This exception will be used as a Cause
// of another exception
Exception
ee
= new Exception("Numbers are not Positive");
// create a new Exception
Exception anotherEXe = new Exception();
// initialize the cause and throw Exception
anotherEXe.initCause(ee);
throw anotherEXe;
}
else {
System.out.println(a + b);
}
}
}
输出:
Cause : java.lang.Exception: Numbers are not Positive