當JVM無聲無息的掛掉,也記不到Log,找不到黑盒子,怎麼辦?到JDK 5.0是有提供一個UncatchExceptionHandler介面,目前有來拿專案測,但有效與否尚待考驗。UncatchExceptionHandler是給thread註冊一個class,在thread丟出無法catch的Exception(Uncatch的由來),UncatchExceptionHandler理應抓得到這個Exception,飯粒如下:
class TestRuntimeException extends Thread
{
// 宣告static class是因為要給static method (main)使用。
static class OverrideExceptionHandler implements Thread.UncaughtExceptionHandler { // Thread.可省略。
public void uncaughtException(Thread t, Throwable e) {
// ... e.getMessage() 會是 java.lang.ArithmeticException: / by zero
}
}
public void run() {
int static_count = 100 / 0; // 除以零Exception
System.out.println("No Run");
}
public static void main(String[] args)
{
TestRuntimeException tr = new TestRuntimeException();
tr.setUncaughtExceptionHandler(new OverrideExceptionHandler());
tr.start();
}
}
上述方式不知可否catch到像記憶體不足,CPU滿載導致Process掛掉的情形,有待驗證。
另外之前也查到另一個方式,但只能在JVM被shutdown後執行,而且也無法得知原因,僅能記錄時間。畢竟涉及到system native call不是JVM能管得到的範圍:
public class ShutdownHookThread extends Thread {
public void run() {
// … handle before JVM shutdown
}
}
public class Main {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread()); // 註冊Shutdown Hook處理thread類別。
// ...
}
}