The getCause() วิธีมาจาก โยนได้ class และเราสามารถใช้วิธีนี้ซึ่งส่งคืน สาเหตุ ข้อยกเว้น หรือ ส่งคืน ว่าง หากไม่ทราบสาเหตุของข้อยกเว้น getCause() เมธอดไม่ยอมรับข้อโต้แย้งใด ๆ และไม่ส่งข้อยกเว้น ส่งกลับสาเหตุที่ได้รับจากหนึ่งในผู้สร้างหรือที่กำหนดโดยการก่อตัวของ 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