How to quit a java app from within the program
What's the best way to quit a Java application with code?
You can use System.exit()
for this purpose.
According to oracle's Java 8 documentation:
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
The call
System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
System.exit(0);
The "0" lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);
, or with another non-zero number corresponding to the specific error.
Also, as others have mentioned, clean up first! That involves closing files and other open resources.