当引用RuntimeException的方法被调用而不处理Java中的异常时,为什么程序不会终止? [英] Why does the program not terminate when a method that throws RuntimeException is called without handling the exception in Java?

查看:436
本文介绍了当引用RuntimeException的方法被调用而不处理Java中的异常时,为什么程序不会终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
    }
}

我没有使用任何try / catch块来捕捉当我在类1中调用good.method()时抛出NullPointerException(它扩展了RunTimeException)。
当我运行程序时,Eclipse中的控制台表示程序仍在运行,因为它不会显示在控制台顶部与程序执行结束时通常一样。

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.

为什么程序仍在运行?

如何使程序执行停止而不用按红色停止按钮?

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.

防止JVM终止的唯一方法是让非守护进程的线程运行。如果您已经显示了GUI,那么您必须确保终止EDT以使应用完全终止。

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.

这篇关于当引用RuntimeException的方法被调用而不处理Java中的异常时,为什么程序不会终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆