Wednesday, May 13th, 2009...12:53 pm

Capturing Uncaught Java Exceptions in a Bash Shell Script

Jump to Comments

I was burned one to many times by chaining dependent java programs together in a bash script.

By default the java executable will return zero if the program exited manually, and 1 if there was an uncaught RuntimeException.

Let’s say test.sh runs a java program, we want to run it 3 times, but if it fails during any of the runs we want to abort our run.

[code]
#!/usr/bin/bash
java Test
exitval=$?
echo "exit val: ${exitval}"
exit $exitval
[/code]

Then in our shell script to run test.sh each time we’d do something like this.
[code]
#!/usr/bin/bash

./test.sh
step1=$?

if [ $step1 -eq "0" ] ; then
./test.sh
step2=$?
if [ $step2 -eq "0" ] ; then
./test.sh
step3=$?
if [ $step3 -eq "0" ] ; then
echo "Finished successfully."
else
echo "Step 3 failed."
fi
else
echo "Step 2 failed with ${step2}"
fi
else
echo "Step 1 Failed. with ${step1}"
fi
[/code]

To test my script I made a little java class that will error out half the time that looks like this:
[java]
import java.util.Random;
public class Test
{

public static void main(String[] args)
{
Random gen = new Random();
if(gen.nextInt(2) > 0)
{
System.out.println(“I Win!”);
}
else
{
throw new RuntimeException(“I Fail!”);
}
}
}

[/java]

3 Comments

Leave a Reply