简体   繁体   English

为什么在ExecutorService实例产生的线程上吞没Java错误?

[英]Why are Java Errors swallowed on threads spawned by an ExecutorService instance?

I thought Java Errors were indications of serious problems and shouldn't be handled. 我认为Java错误是严重问题的征兆,因此不应进行处理。 Why then, does this code run fine? 那么为什么这段代码运行良好?

public static void main(String[] args)
{
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> future = executor.submit(() -> {throw new AssertionError();});
    while (!future.isDone()) {
    }
    System.out.println("done");
}

I had an unimplemented method which threw an AssertionError to remind me to implement it but it just got swallowed up with absolutely no indication that something was seriously wrong. 我有一个未实现的方法,该方法抛出AssertionError来提醒我实现它,但是它完全被吞没了,没有任何迹象表明存在严重错误。

It's not swallowed, it's there: 它不被吞没,在那儿:

public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(() -> {
            throw new AssertionError();
        });
        while (!future.isDone()) {
        }
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("done");
    }

You get the error on calling get method that gives you the result of computation if succeeded or an error otherwise. 您在调用get方法时出错,该方法将为您提供计算结果(如果成功的话),否则返回错误。

java.util.concurrent.ExecutionException: java.lang.AssertionError at java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.util.concurrent.FutureTask.get(FutureTask.java:192) ... java.util.concurrent.ExecutionException:java.util.concurrent.FutureTask.report(FutureTask.java:122)处的java.lang.AssertionError在java.util.concurrent.FutureTask.get(FutureTask.java:192)处...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM