Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của phương thức getCause() trong Java

Throwable.getCause()

Trả về **nguyên nhân gốc** (cause) của exception – là exception khác đã dẫn đến exception hiện tại. Trả về null nếu không có cause.

Cú pháp

public Throwable getCause()

Ví dụ: Wrap exception và lấy cause


public class GetCauseDemo {
    public static void main(String[] args) {
        try {
            myMethod();
        } catch (Exception e) {
            System.out.println("Cause = " + e.getCause());
            // In stack trace đầy đủ
            e.printStackTrace();
        }
    }

    static void myMethod() {
        try {
            int[] arr = {1, 3, 5};
            System.out.println(arr[8]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            // Bọc exception gốc vào exception mới
            Exception wrapped = new Exception("Lỗi xử lý mảng");
            wrapped.initCause(e); // Gán cause
            throw wrapped;
        }
    }
}

Kết quả

Cause = java.lang.ArrayIndexOutOfBoundsException: 8
java.lang.Exception: Lỗi xử lý mảng
    at GetCauseDemo.myMethod(GetCauseDemo.java:18)
    at GetCauseDemo.main(GetCauseDemo.java:6)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 8
    at GetCauseDemo.myMethod(GetCauseDemo.java:14)
    ... 1 more

Khi nào dùng?

  • Exception chaining (wrap checked exception vào unchecked hoặc ngược lại).
  • Logging: giữ nguyên root cause để debug.
  • Frameworks (Spring, Hibernate) dùng rộng rãi.

Lưu ý: initCause(Throwable) chỉ gọi được **một lần** (thường trong constructor hoặc ngay sau khi tạo exception).