提问人:Immanuel Kant 提问时间:7/5/2022 更新时间:7/5/2022 访问量:99
发生异常时,Java setUncaughtExceptionHandler() 不起作用
Java setUncaughtExceptionHandler() doesn't work when exception happen
问:
我有测试代码,看看我是否可以设置异常处理程序:
class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.printf("An exception has been captured\n");
System.out.printf("Thread:%s\n", t.getName());
System.out.printf("Exception: %s: %s:\n", e.getClass().getName(), e.getMessage());
System.out.printf("Stack Trace:\n");
System.out.printf("Thread status:%s\n", t.getState());
}
}
public class TestUncaughtException {
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
System.out.println(Integer.parseInt("ff"));
}
}
使用 maven 运行它,它会打印:
java.lang.NumberFormatException: For input string: "ff"
at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
at java.lang.Integer.parseInt (Integer.java:580)
at java.lang.Integer.parseInt (Integer.java:615)
at TestUncaughtException.main (TestUncaughtException.java:18)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
at java.lang.Thread.run (Thread.java:748)
似乎 MyExceptionHandler 不起作用,因为未调用 uncaughtException。
我哪里做错了?
答: 暂无答案
评论