Java 空指针异常不会终止程序

发布于 2024-12-09 06:11:38 字数 223 浏览 1 评论 0原文

我的问题很简单。当发生异常时如何强制JAVA终止我正在编写的程序?

我当前正在使用 Swing,当抛出 NullPointer 异常时,程序会继续在后台运行:|以这种方式运行时,我只能从任务管理器关闭它。不好的是,当我再次运行同一个程序时,会创建第二个实例,我不知道为什么,但是当我有超过 1 个同一个程序的实例时,一次我得到 null 异常,下一次则不会,下次是,下次不是……完全随机。

提前致谢!

my question is simple. How to force JAVA to terminate the program I am writing when any Exception occures?

I am currenlty using Swing and when a NullPointer exception is thrown, the program keeps on running in the background :| While running this way I can only close it from the task manager. The bad thing is that when I run the same program again, a second instance is created and I don't know why, but when I have more than 1 instance of the same program, one time I get null exception, next time not, next time yes, next time not.... Complete randomness.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

窝囊感情。 2024-12-16 06:11:38

这篇文章将会引起兴趣字。捕获异常(理想情况下,您应该消除异常)。

这个想法是,您可以插入代理来包装 Swing 事件的调用,并捕获任何由此产生的异常。然后你可以决定做什么——提醒某人、退出等。

This article will be of interest wrt. catching exceptions (which, ideally, you should be eliminating).

The idea is that you can plug in a proxy to wrap the invocation of the Swing event, and catch any resultant exceptions. You can then decide what to do - alert someone, exit etc.

堇年纸鸢 2024-12-16 06:11:38

显然,您的程序似乎至少有一个错误,您可以尝试使用调试器来解决该错误。

至于你的问题,如果没有捕获异常,它将终止你的程序。因此,如果你总是抛出异常,包括在 main 方法中,那么一旦发生就会导致程序退出。

然而,正如 Mac 在评论中所说

Swing 应用程序有一个事件循环。事件循环捕获 Throwable(我相信),因此他无法精确控制以正常方式捕获的内容。

Obviously it seems that your program has at least a bug that you can try to iron out with a debugger.

As for your question, an exception will terminate your program if it isn't caught. So if you always throw your exceptions, including in the main method, when one happen will cause the program to exit.

However, as Mac said in the comment

A Swing app has an event loop in the way. The event loop catches Throwable (I believe), so he can't exactly control what's caught in the normal way.

悸初 2024-12-16 06:11:38

您应该修复程序中的错误。如果未捕获异常,则该异常将终止程序,您可能正在捕获该异常。您始终可以使用 System.exit(0); 退出程序

You should fix your bugs in your program. An exception will terminate the program if it isn't caught, you are probably catching the exception. You can always exit a program with System.exit(0);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文