Wednesday, February 11, 2009

Don't use System.exit()!

Just a quick comment/plea about the evils of System.exit() (or whatever other equivalents in other languages if they are anything like Java). Really, 'exit' is like a global variable. You think you want to kill the program, but you really don't. The moment you use it anywhere, you've set up a trap that makes your software unusable by third parties. Consider these alternatives instead:
  • Throw an exception.
  • End your thread, but this is a deep subject of itself which is beyond my current scope.
  • For real newbies (or others) working in main() alone, just use 'return'.
Really, please, and based on real-world pain, leave exit() alone unless that's really really really really really really really what you want. The status code might be one reason, but Java really isn't so often used for writing traditional processes. If you do need that, make sure you have your "traditional process" nicely distinct from the rest of your code.

No comments:

Post a Comment