1

Please, consider the following snippet which is being run from Eclipse.

Even though the external jar file does not exist no Exception is thrown and process is not null. Why is it so?

try {
    Process process = Runtime.getRuntime().exec("java -jar NonExisting.jar");

    if (process == null)
            System.out.println("process = null");
    else
        System.out.println(process);
     } catch (IOException e) {
         System.err.println(e);
}

It prints

java.lang.ProcessImpl@1a4d139

If I run it manully from command line then there is an error:

C:\Users\workspace\Project\src>java -jar NonExisting.jar
Error: Unable to access jarfile NonExisting.jar
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
  • 1
    Because the java process is running/executed. You'll get an error if you try to run a non existing executable. You have to check the java.exe **exit code**. – Adriano Repetti Dec 10 '12 at 11:01
  • As a general tip, follow the link to the JavaWorld article linked from the [exec info. page](http://stackoverflow.com/tags/runtime.exec/info) & follow **all** the recommendations. If that code had done so, the outcome would have been more clear. Also, unless you intend to support 1.4, use `ProcessBuilder` to create the `Process` & separate the `String` arguments into a `String[]`. – Andrew Thompson Dec 10 '12 at 12:43

3 Answers3

2

Process.waitFor() gives you the exit code of the spawned process, and is likely returning a non-zero (i.e. error) value. You should check this value, and collect the stdout/err at the same time (see here for more info). stderr will likely report an error.

All you're currently doing is confirming that the process has been invoked. The process then tries/fails to load the jar file, and that's when it exists and reports an error.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

The process was created and finished. You should check the return value of the Process object. An exception will be thrown if there is a problem with the creation of the new process, so here you don't get an exception.

vainolo
  • 6,907
  • 4
  • 24
  • 47
  • Yes, `exitValue()` returns 1 if the jar does not exist. But now I test with existing jar and `exitValue()` throws `java.lang.IllegalThreadStateException: process has not exited` – Nikolay Kuznetsov Dec 10 '12 at 11:35
1

Whoa, this is quite ugly :-) Why dont you start the Main Methd of the jar in a new thread? Well you should check the exit status of the process:

http://en.wikipedia.org/wiki/Exit_status

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.htm

You are basically forking the process so you cannot get exceptions or anything java specific from this, you need to deal with the new process, like any other OS specific app.

Stefan
  • 990
  • 1
  • 6
  • 10