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

Viewed 22249

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?

7 Answers

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.

Related