UncaughtExceptionHandler เป็น interface ในคลาส Thread ใช้จัดการ Exception ที่ไม่ถูกจับ (Uncaught) ใน Thread ใดๆ เมื่อ Thread จะจบจาก Exception ที่ไม่ได้ catch JVM จะเรียก Handler นี้ ก่อนที่ Thread จะตาย ใช้สำหรับ Logging, ส่ง Log ไป Server, Cleanup ฯลฯ (เพิ่มใน Java 5)
การตั้งค่า Default Handler
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler ueh)
Interface Definition
@FunctionalInterface
public interface UncaughtExceptionHandler {
void uncaughtException(Thread t, Throwable e);
}
ตัวอย่างโค้ด
public class UncaughtExceptionHandlerTest {
public static void main(String[] args) throws Exception {
// ตั้ง Default Handler สำหรับทุก Thread
Thread.setDefaultUncaughtExceptionHandler(new MyHandler());
// โยน Exception ทดสอบ
throw new Exception("Test Exception");
}
private static final class MyHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("The Exception Caught: " + e);
// ที่นี่ทำได้: log to file, send to server, cleanup, alert
}
}
}
ผลลัพธ์
The Exception Caught: java.lang.Exception: Test Exception
การใช้งานแบบ Per-Thread
Thread t = new Thread(() -> {
throw new RuntimeException("Thread error");
});
t.setUncaughtExceptionHandler((thread, throwable) -> {
System.out.println("Thread " + thread.getName() + " failed: " + throwable);
});
t.start();
Use Cases
- Centralized Logging - เก็บ Log ทุก Uncaught Exception ไว้ที่เดียว
- Crash Reporting - ส่งรายงาน Error ไป Server (เช่น Firebase Crashlytics)
- Graceful Shutdown - ปิด Resource, Save State ก่อนจบ
- UI Applications - แสดง Dialog แจ้งผู้ใช้ แทน Crash เงียบๆ
ข้อควรระวัง
- Handler นี้ทำงานเฉพาะ Uncaught Exception (ที่ไม่มี try-catch ครอบ)
- ใน Main Thread โปรแกรมจะจบหลัง Handler รันเสร็จ
- ไม่ควรโยน Exception ใหม่ใน Handler (อาจ Loop)