java System.exit(num) 还是从 main 抛出 RuntimeException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3517655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:12:28  来源:igfitidea点击:

System.exit(num) or throw a RuntimeException from main?

javaexception-handlingerrorlevel

提问by VarV

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?

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

采纳答案by David Z

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

除非您确实有异常情况,否则不要抛出异常。System.exit(int)正是出于这个原因。用它。

EDIT: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.

编辑:我想我可能误读了你的问题。我以为你在问,什么时候你想正常退出 JVM 但发出信号表明事情不太正确,是抛出异常还是使用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.

但是,如果发生的问题已经由 Java 异常指示,则可以不处理该异常。您不必捕获异常并调用System.exit.

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 mainmethod, 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 RuntimeExceptionif necessary.

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

回答by Aaron Novstrup

Generally in this situation I would handle all exceptions in my main method, possibly by calling System.exit. This gives you flexibility about where/whether/how to handle exceptional conditions, while still meeting your need to terminate with an error code. In particular, it gives you control over the return code and any other output you might generate for the user (error message, stack trace, etc). If you throw an exception in main (or let an exception escape), you lose that control.

通常在这种情况下,我会在我的主要方法中处理所有异常,可能通过调用System.exit. 这为您提供了在何处/是否/如何处理异常情况方面的灵活性,同时仍然满足您以错误代码终止的需要。特别是,它使您可以控制返回代码和您可能为用户生成的任何其他输出(错误消息、堆栈跟踪等)。如果您在 main 中抛出异常(或让异常逃逸),您将失去控制。

To summarize, call System.exitonly in your top-level exception handler:

总而言之,System.exit只在您的顶级异常处理程序中调用:

static public void main() {
   try {
      runMyApp();
   } catch (Exception e) {
      System.exit(1);
   }
}

回答by Jes

An exception thrown will print out the stack trace, and if you don't need that, you shoul use System.exit.

抛出的异常将打印出堆栈跟踪,如果您不需要它,您应该使用 System.exit。

Upon exit you can inform the user with a Sytem.out (I assume the app is running in a commanline environment only).

退出时,您可以使用 Sytem.out 通知用户(我假设该应用程序仅在命令行环境中运行)。

You should consider just catching all errors an logging the errors in a seperate log, this ensures the stacktrace is not lost forever when you close the terminal. Take a look at log4j for this purpose, it's really easy to use.

您应该考虑仅捕获所有错误并将错误记录在单独的日志中,这可确保在您关闭终端时堆栈跟踪不会永远丢失。看看为此目的的log4j,它真的很容易使用。

回答by helios

The APP itself should use System.exit. It's its interface with the calling environment (script). Any internal component of course should use Exception. When you put it together it can be the both of'em:

APP 本身应该使用 System.exit。它是它与调用环境(脚本)的接口。任何内部组件当然都应该使用 Exception。当你把它放在一起时,它可以是两者:

Application.main(...) {
  parse(args);
  check(...);
  try {
    MyObject o = ...;
    o.doMyStuff();
  } catch (Exception e) {
    System.err.println("Oops, something went wrong!"); // by example, or use a logging framework! // anyway in a shell app System.in/out/err IS my interface with the outworld
    System.exit(ERROR_CODE);
  }
  System.out.println("Worked!");
}

回答by Foumpie

It depends how much information you want to report back to the script that starts your program. This can be very important if the script is designed to execute a chain of actions. https://shapeshed.com/unix-exit-codes/

这取决于您想要向启动程序的脚本报告多少信息。如果脚本旨在执行一系列操作,这可能非常重要。https://shapeshed.com/unix-exit-codes/

Example: I developed a Java program that calls an external API, downloads the response and saves it to a file. Possible outcomes:

示例:我开发了一个 Java 程序,该程序调用外部 API,下载响应并将其保存到文件中。可能的结果:

  • 0 = OK
  • 5 = HTTP Temporarily unavailable
  • 6 = Unable to write file to disk
  • 0 = 正常
  • 5 = HTTP 暂时不可用
  • 6 = 无法将文件写入磁盘

Now my script knows what went wrong, and it could take different actions based on the outcome.

现在我的脚本知道出了什么问题,它可以根据结果采取不同的行动。

  • If response = 0, continue next step in the script
  • If response = 5, retry (with a delay)
  • If response = 6, stop the script
  • 如果响应 = 0,则继续脚本中的下一步
  • 如果响应 = 5,重试(延迟)
  • 如果 response = 6,停止脚本

Bottom line: like any good api, clearly define your input and output parameters and use System.exit.

底线:像任何好的 api 一样,明确定义您的输入和输出参数并使用System.exit.

回答by Manish Malhotra

System.exit(num) is not a good option, as its shutdown JVM, plus even it didnt run the finally block if you have after catch block.

System.exit(num) 不是一个好的选择,因为它关闭了 JVM,而且如果你有 after catch 块,它甚至没有运行 finally 块。

Throwing RuntimeException also might not be the best of the option, can subclass as mentioned earlier which is app specific exception could be a better option in my opinion. -Manish

抛出 RuntimeException 也可能不是最好的选择,可以像前面提到的那样子类化,这是应用程序特定的异常在我看来可能是更好的选择。-Manish

回答by Harsha Hulageri

System.exit() not recommended. It shutdowns JVM.

不推荐 System.exit()。它关闭JVM。