Java 空指针异常不会终止程序
我的问题很简单。当发生异常时如何强制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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这篇文章将会引起兴趣字。捕获异常(理想情况下,您应该消除异常)。
这个想法是,您可以插入代理来包装 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.
显然,您的程序似乎至少有一个错误,您可以尝试使用调试器来解决该错误。
至于你的问题,如果没有捕获异常,它将终止你的程序。因此,如果你总是抛出异常,包括在 main 方法中,那么一旦发生就会导致程序退出。
然而,正如 Mac 在评论中所说
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
您应该修复程序中的错误。如果未捕获异常,则该异常将终止程序,您可能正在捕获该异常。您始终可以使用
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);