gpt4 book ai didi

java - UncaughtExceptionHandler 未调用

转载 作者:行者123 更新时间:2023-11-30 02:02:06 26 4
gpt4 key购买 nike

我在 Groovy/Java 中使用 UncaughtExceptionHandler 时遇到问题。

class UncaughtExceptionLogger implements Thread.UncaughtExceptionHandler {

@Override
void uncaughtException(Thread t, Throwable e) {
//TODO do some logging;
println "test";
}

主要..groovy

def main(){
def handler = new UncaughtExceptionLogger();
Thread.defaultUncaughtExceptionHandler = handler
String s;
s.charAt(10); // causes a NullPointerException but the exception handler is not called
}

main();

为什么我期望在抛出 NullPointerException 时调用异常处理程序,但这并没有发生。我做错了什么?

最佳答案

似乎你必须用单独的线程生成它:

class UncaughtExceptionLogger implements Thread.UncaughtExceptionHandler {
@Override
void uncaughtException(Thread t, Throwable e) {
//TODO do some logging;
println "test";
}
}

def main(){
Thread.defaultUncaughtExceptionHandler = new UncaughtExceptionLogger()
String s;
s.charAt(10); // causes a NullPointerException but the exception handler is not called
}

Thread.start {
main()
}

关于java - UncaughtExceptionHandler 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52511120/

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