
getCause() 方法来自 Throwable 类,我们可以使用此方法返回原因 异常或返回null(如果异常原因未知)。 getCause() 方法不接受任何参数,也不会引发异常。它返回由其构造函数之一提供的原因或由 Throwable 类的 initCause()方法的形成确定的原因。
语法
public Throwable getCause()
示例
public class GetCauseMethodTest {
public static void main(String[] args) throws Exception {
try {
myException();
} catch(Exception e) {
System.out.println("Cause = " + e.getCause());
}
}
public static void myException() throws Exception {
int arr[] = {1, 3, 5};
try {
System.out.println(arr[8]);
} catch(ArrayIndexOutOfBoundsException aiobe) {
Exception e = new Exception();
throw(Exception); <strong>/</strong>/ throwing the exception to be caught by catch block in main()
e.initCause(aiobe); // supplies the cause to getCause()
}
}
}输出
Cause = java.lang.ArrayIndexOutOfBoundsException: 8











