gpt4 book ai didi

java - UncaughtExceptionHandler 更改异常消息

转载 作者:行者123 更新时间:2023-12-02 06:43:15 24 4
gpt4 key购买 nike

小例子:

 public class App {   
public static void main(String[] args) {
throw new RuntimeException("Test exception");
}
}

按预期打印以下内容:

Exception in thread "main" java.lang.RuntimeException: Test exception
at App.main(App.java:5)

让我们修改这个程序:

public class App {    
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof RuntimeException) throw (RuntimeException)e;
}
});
throw new RuntimeException("Test exception");
}
}

打印:

Exception: java.lang.RuntimeException thrown from the UncaughtExceptionHandler in thread "main"

问题:

为什么消息不包含任何有关其发生位置的信息,并且没有堆栈跟踪、消息?

对于我来说,异常消息看起来很奇怪。

最佳答案

Java API 文档说:

void uncaughtException(Thread t, Throwable e)

Method invoked when the given thread terminates due to the given uncaught exception. Any exception thrown by this method will be ignored by the Java Virtual Machine.

因此,如果您希望程序在某些异常时终止并打印它们的消息/堆栈跟踪,您应该这样做:

        @Override
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof RuntimeException) {
e.printStackTrace();
System.exit(1);
}
}

关于java - UncaughtExceptionHandler 更改异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18912439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com