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

会有一股神秘感。 提交于 2019-12-24 03:00:34

问题


Class 1:

package hf;

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

        good.method();
    }
}

Class 2:

package hf;

public class Goodie extends NullPointerException
{

}

Class 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.

Why is the program still running?

How can I bring the program execution to halt without pressing the red stop button?


回答1:


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. If you have displayed a GUI for instance, you must make sure you terminate the EDT to for the application to terminate completely.




回答2:


When we run an app in debug mode in Eclipse it will stop on uncaught exceptions if Windows->Preferences->Java->Debug->Suspend execution on uncaught exceptions is set.



来源:https://stackoverflow.com/questions/27297654/why-does-the-program-not-terminate-when-a-method-that-throws-runtimeexception-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!