Trap and write out error to file

J

John Leslie

I am using the following borrowed code to run unix commands.
Occasionally it returns 3, apparently without actually running the
command and I do not know why.

I would like to get more info on the error and write it to a file.

As I am not a java programmer can someone help me amend the code to
write the error details of the t object to a file?

Thanks in advance.



Runtime rt = Runtime.getRuntime();
Process p = rt.exec(Command);
try {
rc = p.waitFor();
} catch (InterruptedException intexc) { rc = 2; }

rt.gc();
} catch (Throwable t) { rc = 3; }
 
F

Fred L. Kleinschmidt

John said:
I am using the following borrowed code to run unix commands.
Occasionally it returns 3, apparently without actually running the
command and I do not know why.

I would like to get more info on the error and write it to a file.

As I am not a java programmer can someone help me amend the code to
write the error details of the t object to a file?

Thanks in advance.

Runtime rt = Runtime.getRuntime();
Process p = rt.exec(Command);
try {
rc = p.waitFor();
} catch (InterruptedException intexc) { rc = 2; }

rt.gc();
} catch (Throwable t) { rc = 3; }

This second "catch" clause is illegal - it has no associated "try" (it
would be OK if the rt.gc() call were removed, since it would then be
associated with the first "try".

You should not use rc both as the return for p.waitFor() and as a flag
you set if there is an error. What if p.waitFor returns 2 or 3? How
would your code distinguish whether an error had occurred?

You can print the exception message to stderr easily:
System.err.println( t.getMessage() );
 
N

news.rcn.com

Maybe you need to find out if the external command is running or not. Try
rt.exec ( Command + " > /tmp/myRuntimeOutput.out 2>&1" )
to capture stdout and stderr into a file.

If the exec() call returns '3', which you get back from waitFor(), your Unix
command probably failed. This could look like it didn't execute because the
error messages will sail off into the ether if you don't grab it and
redirect it into a file.

Hope this helps.

jim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top