Java中getCause()方法的重要性?
的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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短