Java 中 getCause() 方法的重要性?\n
getCause() 方法来自 Throwable 类,我们可以使用该方法,它返回异常的 cause 或在异常的 cause 不知道时返回 null。getCause() 方法不接受任何参数,也不抛出异常。它返回由其一个构造函数提供的或由 Throwable 类 initCause() 方法的形成确定的 cause。
语法
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP