在Eclipse中抛出未检查的异常时,从新创建的线程打印堆栈跟踪 [英] Printing the stack trace from a newly created thread when an unchecked exception is thrown in Eclipse
问题描述
如果从主线程不同的线程抛出未检查的异常,为什么在Eclipse的控制台中无法看到堆栈跟踪?例如: p>
ScheduledThreadPoolExecutor scheduledExecutor;
scheduledExecutor.scheduleAtFixedRate(new Log(),0,LOGGING_FREQUENCY_MS,TimeUnit.MILLISECONDS);
public class Log实现Runnable {
public void run(){
//抛出NullPointerException
}
}
我没有输出。但是如果我这样做:
ScheduledThreadPoolExecutor scheduledExecutor;
scheduledExecutor.scheduleAtFixedRate(new Log(),0,LOGGING_FREQUENCY_MS,TimeUnit.MILLISECONDS);
public class Log实现Runnable {
public void run(){
try {
// NullPointerException抛出
} catch(异常e){
e.printStackTrace();
}
}
}
我可以看到堆栈跟踪
为什么?
编辑:后续问题:打印由线程池线程抛出的异常的最简单的方法?为每一个Runnable添加try-catch当然是非常难看的。
因为Executor已经吞没了异常。您可以通过查询返回的未来来查看是否有人:
未来<?> f = scheduledExecutor.scheduleAtFixedRate(new Log(),...);
try {
f.get();
} catch(ExecutionException e){
Throwable actualException = e.getCause();
}
请注意, f.get()
将阻塞,直到任务被取消或引发异常,所以你可能想在一个单独的线程中调用它。
Why am I unable to see the stack trace in Eclipse's console when an unchecked Exception is thrown from a thread different from the main thread?
For example:
ScheduledThreadPoolExecutor scheduledExecutor;
scheduledExecutor.scheduleAtFixedRate(new Log(), 0, LOGGING_FREQUENCY_MS, TimeUnit.MILLISECONDS);
public class Log implements Runnable {
public void run() {
//NullPointerException is thrown
}
}
I get no output. But if I do:
ScheduledThreadPoolExecutor scheduledExecutor;
scheduledExecutor.scheduleAtFixedRate(new Log(), 0, LOGGING_FREQUENCY_MS, TimeUnit.MILLISECONDS);
public class Log implements Runnable {
public void run() {
try {
//NullPointerException is thrown
}catch(Exception e){
e.printStackTrace();
}
}
}
I can see the stack trace.
Why?
EDIT: Follow-up question: What would be the easiest way to print the exceptions thrown by thread-pool threads? Adding try-catch to every single Runnable is of course really ugly.
Because the Executor has "swallowed" the exception. You can see if you got one by querying the returned future:
Future<?> f = scheduledExecutor.scheduleAtFixedRate(new Log(),...);
try {
f.get();
} catch (ExecutionException e) {
Throwable actualException = e.getCause();
}
Note that f.get()
will block until the task is cancelled or throws an exception so you will probably want to call it in a separate thread.
这篇关于在Eclipse中抛出未检查的异常时,从新创建的线程打印堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!