What's the best practice to calling System.exit(0)
?
I am intentionally calling System.exit(0)
. What's the proper way to call System.exit(0)
?
Should I just create a method that calls System.exit(0)
?
Thanks.
What's the best practice to calling System.exit(0)
?
I am intentionally calling System.exit(0)
. What's the proper way to call System.exit(0)
?
Should I just create a method that calls System.exit(0)
?
Thanks.
"Best Practice" actually grounds on what on you want to execute.
If you really do wish to terminate the program immediately, rather than letting upper levels of the program decide what to do, you should call: System.exit(1)
(or some other non-zero positive exit status).
An exit code of 0
says to the shell (and parent processes) that execution completed normally;
Positive exit codes report that there was an error. Something you expected that could go wrong went actually wrong;
Negative exit code is when something you didn't expect went wrong (system error - unanticipated exception - externally forced termination e.g. kill -9
);
The motivation for this warning (I'm guessing you are looking at a findbugs result, but many other tools have this too) is as follows:
When you call System.exit()
directly. You are unable to use this code inside a unit test or an application server. As in both cases you code is ran inside a framework and you don't want this framework to exit.
However, when you have a stand alone application, you might eventually want to exit. This can be done in two ways: end the execution of all non-demon threads by making them finish their tasks, or by calling System exit. In large applications using 3rd party libraries, the first option often is not viable or possible.
So I personally try to limit my applications to do one or two System exits (such as when the user requests the application to close). Keep them out of any parts of the code that are complex, so you can test and reuse those.
A Guid to System.exit() https://www.baeldung.com/java-system-exit