เมธอด getCause() จากคลาส Throwable คืน สาเหตุ (Cause) ของ Exception หรือ null หากไม่ทราบสาเหตุ ไม่รับพารามิเตอร์ ไม่โยน Exception คืนค่าที่ให้มาผ่าน Constructor หรือ initCause()
ไวยากรณ์
public Throwable getCause()
ตัวอย่าง: ใช้ getCause() และ initCause()
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]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException aiobe) {
Exception e = new Exception();
e.initCause(aiobe); // กำหนด Cause ให้ Exception ใหม่
throw e; // โยน Exception ใหม่พร้อม Cause
}
}
}
ผลลัพธ์
Cause = java.lang.ArrayIndexOutOfBoundsException: 8
การใช้งาน: Exception Chaining - ห่อ Exception ต้นทาง (Cause) ไว้ใน Exception ใหม่ เพื่อให้ Stack Trace แสดงทั้งสองชั้น ช่วย Debugging ได้ดีขึ้น