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

前端 未结 7 1827
日久生厌
日久生厌 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:09

    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/

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

    • 0 = OK
    • 5 = HTTP Temporarily unavailable
    • 6 = Unable to write file to disk

    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

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

提交回复
热议问题