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