How exactly works the Java application exit code o

2019-03-24 17:20发布

问题:

I have the following doubts related a simple command line Java application.

So I have this command line application that is startd by a main() method definied inside a Main class.

As usual this main() method is definied with this signature:

public static void main(String[] args) {

So it return type is void. So it should mean that it don't return any value.

But why when its execution correctly terminates I obtain this message into the IntelliJ console?

Disconnected from the target VM, address: '127.0.0.1:54090', transport: 'socket'

Process finished with exit code 0

What exactly represent the exit code 0?

I think that it means that the program have correctly complete its execution without incur into any error.

So now I have the following 2 doubts:

  1. If it is true why it happens if my main() method return void?

  2. How can I return a different exit code if my application end with an error? Exist a standard exit code value for ending with errors?

Tnx

回答1:

The VM exits when

  • all of the non-daemon threads stop running, or
  • System.exit(exitCode) is called

In 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.



回答2:

An exit code of 0 means it completed normally, that is standard for all processes, not just java. The value is not returning from the main method (it's void) but from the JVM itself.

A different value can be specified, e.g. System.exit(1) to indicate some error condition, and the program stops.



回答3:

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.