0

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.

2
  • 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? Commented Aug 13, 2020 at 14:12
  • 1
    Return a code from your Java program using System.Exit. Use that code to determine what to do next in your shell script. Example here. Commented Aug 13, 2020 at 14:14

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.