gpt4 book ai didi

java - 没有异常输出

转载 作者:搜寻专家 更新时间:2023-11-01 01:38:57 24 4
gpt4 key购买 nike

为什么这段代码不打印异常堆栈跟踪?

public class Playground {

/**
* @param args
*/
public static void main(String[] args) {
startThread();
}

private static void startThread() {
ScheduledExecutorService timer = Executors
.newSingleThreadScheduledExecutor();
Runnable r = new Runnable() {
int dummyInt = 0;
boolean dummyBoolean = false;

@Override
public void run() {
dummyInt = Integer.parseInt("AAAA");

if (dummyBoolean) {
dummyBoolean= false;
} else {
dummyBoolean= true;
}

}

};

timer.scheduleAtFixedRate(r, 0, 100, TimeUnit.MILLISECONDS);

}

}

我怎样才能得到它?

我希望看到这个:

java.lang.NumberFormatException: For input string: "AAAA"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Playground$1.run(Playground.java:25)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

最佳答案

执行器可能在线程上设置了自己的未捕获异常处理程序,因此堆栈跟踪不会打印到控制台。如果在 Runnable 中抛出异常,您可以从 scheduleAtFixedRate 方法返回的 ScheduledFuture 对象中获取它:

ScheduledFuture<?> future = timer.scheduleAtFixedRate(r, 0, 100, TimeUnit.MILLISECONDS);
try {
future.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
cause.printStackTrace();
}

关于java - 没有异常输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2459194/

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