简体   繁体   English

为什么在不处理Java中异常的情况下调用引发RuntimeException的方法时,程序不会终止?

[英]Why does the program not terminate when a method that throws RuntimeException is called without handling the exception in Java?

Class 1: 第1类:

package hf;

public class apples
{
    public static void main(String[] args)
    {
        Good good = new Good();

        good.method();
    }
}

Class 2: 第2类:

package hf;

public class Goodie extends NullPointerException
{

}

Class 3: 第3类:

package hf;

public class Good 
{
    public void method() throws Goodie
    {
        System.out.println("Goodmethod");
        throw new Goodie();
    }
}

I have not used any try/catch block to catch the NullPointerException(which extends RunTimeException) that is thrown when I call good.method() in class 1. When I run the program, the console in Eclipse indicates that the program is still running because it does not show at the top of the console box, like it usually does when the program execution is over. 我没有使用任何try / catch块来捕获在类1中调用good.method()时抛出的NullPointerException(扩展RunTimeException)。当我运行该程序时,Eclipse中的控制台指示该程序仍在运行因为它不显示在控制台框的顶部,就像程序执行结束时通常会显示的那样。

Why is the program still running? 为什么程序仍在运行?

How can I bring the program execution to halt without pressing the red stop button? 如何在不按红色停止按钮的情况下停止程序执行?

The program you have posted will terminate when you throw the uncaught exception. 当您引发未捕获的异常时,您发布的程序将终止。 I just tested it myself. 我只是自己测试过。

The only way to prevent the JVM from terminating is to have non-daemon threads running. 防止JVM终止的唯一方法是运行非守护程序线程。 If you have displayed a GUI for instance, you must make sure you terminate the EDT to for the application to terminate completely. 例如,如果显示了GUI,则必须确保将EDT终止为该应用程序才能完全终止。

当我们在Eclipse中以调试模式运行应用程序时,如果设置了Windows->Preferences->Java->Debug->Suspend execution on uncaught exceptions ,它将在未捕获的异常上停止。

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

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