Java Throwable getCause()方法与示例
抛出类getCause()方法
getCause()方法在java.lang包中可用。
getCause()方法用于返回此可抛出异常的原因,当原因不存在或未知时,它返回null。
getCause()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
返回该对象的原因时,getCause()方法不会引发异常。
语法:
public Throwable getCause();
参数:
它不接受任何参数。
返回值:
该方法的返回类型为Throwable,当原因存在或已知时,它将返回此异常的原因;否则,当原因不存在或未知时,它将返回null。
示例
//Java程序演示示例
//ThrowablegetCause()方法的介绍
public class GetCause {
public static void main(String args[]) throws Exception {
try {
//调用div()方法
div(100, 0);
} catch (ArithmeticException ex) {
//显示异常原因的原因
//抛出
System.out.println("Exception Cause:" + ex.getCause());
}
}
//此方法将两个数相除,然后
//引发异常
public static void div(int d1, int d2) throws Exception {
try {
int res = d1 / d2;
} catch (ArithmeticException ex) {
//创建一个异常
ArithmeticException ae = new ArithmeticException();
//实例化异常原因
ae.initCause(ex);
//引发异常 with its cause
throw (ae);
}
}
}输出结果
Exception Cause:java.lang.ArithmeticException: / by zero