System.exit(num)或从main中抛出一个RuntimeException? [英] System.exit(num) or throw a RuntimeException from main?

查看:214
本文介绍了System.exit(num)或从main中抛出一个RuntimeException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单线程应用程序,如果有问题,应该将DOS错误级别设置为非零。抛出RuntimeException或使用System.exit(非零)更好吗?我不需要堆栈跟踪,我不期望这个应用程序被扩展/重用。这两个选项有什么区别?

I've got a single threaded app that should set the DOS errorlevel to something non-zero if there is a problem. Is it better to throw a RuntimeException, or to use System.exit(nonzero)? I don't need the stack trace, and I don't expect this app to be extended/reused. What are the differences between these two options?

推荐答案

除非您真的有异常条件,否则不要抛出异常。 System.exit(int)正是出于这个原因。使用它。

Don't throw an exception unless you really have an exceptional condition. System.exit(int) is there for precisely this reason. Use it.

编辑:我想我可能误读了你的问题。我以为你在问,当你想要正常退出JVM,但是发现一些东西不太顺利,不管是抛出异常还是使用 System.exit

I think I may have misread your question. I thought you were asking, when you want to exit the JVM normally but signal that something did not quite go right, whether it is better to throw an exception or to use System.exit.

但是,如果出现的问题是Java异常已经表明的问题,只要让该异常处理就可以了。您不需要捕获异常并调用 System.exit

However, if the problem that occurs is something which is already indicated by a Java exception, it's fine to just let that exception go unhandled. You don't have to catch the exception and call System.exit.

如果您有选择是否抛出你自己的异常或调用 System.exit ,考虑错误条件是否可能被某些调用方法的Java代码可能被处理。如果错误直接发生在 main 方法中,那么可能永远不会有一个调用者来处理异常,所以你应该调用 System.exit 。否则,通常最好抛出一个异常 - 但不是 RuntimeException ,您应该可以使用适当地表示您遇到的错误的异常类型。如果需要,请编写自己的子类 RuntimeException

If you have a choice of whether to throw an exception of your own or call System.exit, think about whether the error condition is something that might conceivably be handled by some Java code that calls your method. If the error occurs directly in the main method, then there will probably never be a caller to handle the exception so you should probably call System.exit. Otherwise, it's generally best to throw an exception - but not RuntimeException, you should probably use an exception type that appropriately represents the error you encountered. Write your own subclass of RuntimeException if necessary.

这篇关于System.exit(num)或从main中抛出一个RuntimeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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