Alternatives To System.exit(1)


Answer :

The use of System.exit is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the System.exit could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option.

If the java application is really meant to be run as a standalone application, there is nothing wrong with using System.exit. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process.


I agree with the "throw an Exception" crowd. One reason is that calling System.exit makes your code difficult to use if you want other code to be able to use it. For example, if you find out that your class would be useful from a web app, or some kind of message consuming app, it would be nice to allow those containers the opportunity to deal with the failure somehow. A container may want to retry the operation, decide to log and ignore the problem, send an email to an administrator, etc.

An exception to this would be your main() method; this could trap the Exception, and call System.exit() with some value that can be recognized by the calling process or shell script.


System.exit() will block, and create a deadlock if the thread that initiated it is used in a shutdown hook.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable