Search code examples
javashellexit-code

How to detect that the JVM exited abnormally due to an error?


When invoking the JVM with wrong arguments, I'd expect it to exit with an error code:

java -x && echo ok || echo Failed AS EXPECTED
Unrecognized option: -x
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Failed AS EXPECTED

Now, if I use another unrecognized argument, it does exit promptly, but it doesn't return an error code:

# Now that's a CAPITAL X
java -X 2>/dev/null && echo ok || echo Failed AS EXPECTED
ok
  1. Why there's no error code in this case?
  2. How can I detect that the JVM didn't have a chance to run, given that I don't get an error code?

Solution

  • There is no error because -X (capital x) is a valid command line argument.

    It makes Java print help on extra options to the error stream.