For various reasons calling System.exit
is frowned upon when writing Java Applications, so how can I notify the calling process that not everything is going according to plan?
Edit: The 1 is a standin
for any non-zero exit code.
The main alternative is Runtime. getRuntime(). halt(0) , described as "Forcibly terminates the currently running Java virtual machine". This does not call shutdown hooks or exit finalizers, it just exits.
Exit a Java Method using Return There is one more way to exit the java program using return keyword. return keyword completes execution of the method when used and returns the value from the function. The return keyword can be used to exit any method when it doesn't return any value.
because invoking System. exit() kills your JVM, invoking this from Tomcat or Jetty, will not only kill your application but the most likely server itself. This can be potentially dangerous if that server also hosts other critical applications, which is not uncommon at all. As per my experience, System.
System. exit function has status code, which tells about the termination, such as: exit(0) : Indicates successful termination. exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.
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.
Our company's policy is that it's OK (even preferred) to call System.exit(-1), but only in init() methods. I would definitely think twice before calling it during a program's normal flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With