为什么我看不到 java 守护线程抛出的异常

Why can't I see exception thrown out from java daemon thread

我写了一段Java代码来测试线程,比如:

public static void main(String[] args) {

        Thread t = new Thread(() -> {
                throw new NullPointerException();
        });
        t.setDaemon(true);
        t.start();
    }

我希望看到类似的内容:

Exception in thread "Thread-0" java.lang.NullPointerException
    at com.cisco.ruan.nio.Java8Time.lambda[=12=](Java8Time.java:23)
    at java.lang.Thread.run(Thread.java:745)

但是没有打印出来,除非我评论 t.setDaemon(true);

我的问题是为什么在守护线程中弹出异常时没有消息。这样设计的目的是什么?

因为JVM会在抛出异常之前退出,或者记录。

引用自https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon(boolean)

The Java Virtual Machine exits when the only threads running are all daemon threads.

尝试在 t.start() 之后立即执行 Thread.sleep(1000) 以查看消息是否已记录。