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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短