Search code examples
javaprogram-entry-pointerror-code

Can main method return error code if program crashes?


I am wondering if the

public static void main (String args [])

can return any error code if the program crashes? And if not, why is this so? Is it only because of the return type void? If I were to change the return type to something else, would it then be able to return error code?

I have naturally searched the Internet for this and I am sure someone has asked something similarly, but I still don't really understand the reason behind it.


Solution

  • can return any error code if the program crashes?

    No, since the return type is void.

    But exiting a Java program doesn't happen when the main method returns. It happens when the last non-daemon thread stops, or when System.exit() is called. And System.exit() takes an integer as argument. So if you want your Java process to end with status 42, all you need to do is call System.exit(42).