I have the following doubts related a simple command line Java application.
So I have this command line application that is started by a main()
method defined inside a Main class. As usual this main()
method is defined with this signature:
public static void main(String[] args) {
It's return type is void
, and that should mean it doesn't return any value. But when its execution correctly terminates I obtain following message in the IntelliJ console.
Disconnected from the target VM, address: '127.0.0.1:54090', transport: 'socket' Process finished with exit code 0
What exactly does represent the exit code 0
? I think it means that the program have correctly completed its execution without incur into any error.
So now I have the following 2 doubts:
If it is true why it happens if my main()
method return void
?
How can I return a different exit code if my application ended with an error?
Is there a standard exit code value for ending with errors?
The java. lang. System. exit() method exits current program by terminating running Java virtual machine.
System. exit() method. This method terminates the currently running Java Virtual Machine(JVM). It takes an argument “status code” where a non zero status code indicates abnormal termination.
If your program is a console mode program and it's doing output, Ctrl-C should be able to kill it. If it's a GUI program, you'll want to give it a button to exit, or at least setting EXIT_ON_CLOSE as the defaultCloseOperation of your main JFrame.
Exiting with a code of zero means a normal exit: System. exit(0); We can pass any integer as an argument to the method. A non-zero status code is considered as an abnormal exit.
The VM exits when
System.exit(exitCode)
is calledIn the first case, the exit code is 0. In the second case, it's the exit code passed to the exit()
method.
Don't forget that even if your main() method returns, the program will continue running until no non-daemon thread runs anymore. And any thread running in the VM can choose to exit explicitely.
The exit code 0 means that everything went as expected. you can choose to use any other exit code to signal an exceptional condition to the environment.
Exit code of process is what process reports to operating system as its error code.
Java designers could make main()
method to return int
so that JVM could report to OS this value as a process exit code. But they decided to make main void but provide API that can update this code using System.exit(exitCode)
. The advantage of this solution is that program can decide to exit at any point and in any thread, not only in main method and in main thread.
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