的getCause()方法是从Throwable的类,我们可以用这种方法它返回原因的异常的或返回零,如果异常的原因是未知的。该的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); // throwing the exception to be caught by catch block in main() e.initCause(aiobe); // supplies the cause to getCause() }
}
}
输出结果Cause = java.lang.ArrayIndexOutOfBoundsException: 8