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

前端 未结 7 1807
日久生厌
日久生厌 2020-12-18 19:57

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.ex

相关标签:
7条回答
  • 2020-12-18 20:33

    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.

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

    static public void main() {
       try {
          runMyApp();
       } catch (Exception e) {
          System.exit(1);
       }
    }
    
    0 讨论(0)
提交回复
热议问题