Search code examples
javaexceptionprocesstry-catchexit-code

how can java catch exit code from inside java?


my java code runs a main method that throws exit code.

How can I catch that exit code and not stop the runtime?

        ConfigValidator.main(new String[] {"-dirs", SdkServiceConfig.s.PROPERTIES_FILE_PATH});

I thought to use

        ProcessBuilder builder = new ProcessBuilder(commands);
        Process process = builder.start();
        int waitFor = process.waitFor();
        int a = process.exitCode()

but how can i run this to run java code?

I cannot change the code inside the "main" method


Solution

  • The java code does not throw an exit code.

    That's because an exit code is an integer, and you cannot throw an integer, you can only throw an exception.

    The java code exits with an exit code.

    (I wish I could say that the java code returns an exit code, but unfortunately, the designers of the java language decided to make the main() function return void instead of an exit code, which makes things a bit difficult.)

    The following stackoverflow answer suggests to use a security manager that prevents invocation of System.exit(). So, an attempt to invoke System.exit() will result in a SecurityException, and then you can catch that exception from the point where you invoke the main() function.

    Stackoverflow: Java: How to test methods that call System.exit()?

    But of course the right way to do things is to restructure main() so that it does not invoke System.exit() so that you do not have to do hacky things like that.