没有异常输出

时间:2010-03-17 00:39:04

标签: java multithreading exception executorservice

为什么此代码不会打印异常堆栈跟踪?

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)

3 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

执行程序服务由于某种原因倾向于吞下异常。它可以使调试非常具有挑战性。只需在run方法的内容中添加一个try catch,如下所示:

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

    if (dummyBoolean) {
      dummyBoolean= false;
    } else {
      dummyBoolean= true;
    }
  } catch (Exception e){
    e.printStackTrace();
  }

}

Here's一个相关的问题。

答案 2 :(得分:0)

有一个类似的问题在StackOverflow上提供答案Unhandled exceptions with Java scheduled executors

基本上您可以在scheduleAtFixedRate() javadoc中阅读:

  

如果执行了任务   遇到异常,随后   执行被压制

因此,我从这里概括说,通过ScheduledExecutorService.scheduleAtFixedRate()提交任务时,您永远不会看到例外。