I am running java program from shell script. I need to execute next step in same shell script based on if any exception occur in java program or it ran successful.I am aware that java doesn’t run anything. How can we do it in shell script ? I know that we can print some string in log and grep it to check the status. is there any better way to do this ? It would be good even if I can get some elegant way to do it using grep.
-
By "any exception" - do you mean exceptions that were caught and handled by the Java program, or exceptions that were not caught and forced the program to terminate?Joni– Joni2020-08-13 14:12:22 +00:00Commented Aug 13, 2020 at 14:12
-
1Return a code from your Java program using System.Exit. Use that code to determine what to do next in your shell script. Example here.Robert Harvey– Robert Harvey2020-08-13 14:14:21 +00:00Commented Aug 13, 2020 at 14:14
Add a comment
|
1 Answer
If a Java program was terminated because of an exception, the JVM will exit with an error status 1, instead of the usual success status 0. For example, this program exits because of a NullPointerException:
shell$ cat Throw.java
public class Throw {
public static void main(String[] args) {
String s = null;
System.out.println(s.length());
}
}
shell$ java Throw 2>/dev/null; echo $?
1
You can use the exit status in a shell if-statement for example. This will print boo:
if java Throw 2>/dev/null ; then
echo woo
else
echo boo
fi
If you want to set an exit code other than 1, use the System.exit(int status) function.