Wednesday, May 13th, 2009...12:53 pm
Capturing Uncaught Java Exceptions in a Bash Shell Script
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.
java Test
exitval=$?
echo "exit val: ${exitval}"
exit $exitval
Then in our shell script to run test.sh each time we'd do something like this.
./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
To test my script I made a little java class that will error out half the time that looks like this:
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!");
}
}
}







4 Comments
October 29th, 2009 at 3:51 pm
"Мне нравятся Ваши посты"
January 20th, 2010 at 11:45 am
Your my hero!
March 4th, 2010 at 2:37 pm
That's cool... I needed that about a year ago!
September 1st, 2010 at 8:42 am
This has definitely sparked up an idea in my mind. This really is a amazing weblog article.
Leave a Reply