prasad
prasad

Reputation: 359

How to print only exit code ,when java program gives exception(running java program from shellscropt)?

I have a java program which throws some exception,I tried executing it from shell script and printing 0 on failure and 1 on successful execution of java program.But It also printing the Exception onto console I just want to print exit code only.How to do this ?.Any suggestion are appreciated .

following are my Java program and script files Test.Java

public class EchoTest {
    public static void main (String args[]) {
    System.out.println ("scuccess Prasad Bezavada "+(2/0));
    }
} 

Test.sh(script file)

java Test
if [ $? -eq 0 ]
then echo "1"
else echo "0"
fi

getting the following out put

$sh Test.sh
    Exception in thread "main" java.lang.ArithmeticException: / by zero
        at EchoTest.main(EchoTest.java:3)
    0
$

Expecting output is like below(i.e just want to skip the exception message)

$sh Test.sh 0 $

Upvotes: 3

Views: 3534

Answers (3)

First of all, you would like your Java program to return a value (either 1 or 0). In our case we will consider that if an exception is thrown, 1 will be returned and 0 otherwise. Also, exception will be hid (which is a bad practice. You should always log exceptions at least if you are not willing to show it on screen)

public class EchoTest {
    public static void main (String args[]) {
        try {
            System.out.println ("scuccess Prasad Bezavada "+(2/0));
            System.exit(0);
        }
        catch (Exception e) {
            // log your exception here
            System.exit(1);
        }
    }
} 

Once this is done then what you will need to work on is on getting java's output code.

java Test
output = $?
# do some logic here..
if [[ $output -eq 0 ]]; then
    echo "executed"
else
    echo "exception thrown"
fi

Finally, this will indeed return either 1 or 0 depending on execution ignoring exception case, which is what you actually requested.

Upvotes: 0

malarres
malarres

Reputation: 2946

you have to catch the exceptions. After that, you would be able to output exactly what you want. on your example:

public class EchoTest {
public static void main (String args[]) {
    try{
        System.out.println ("scuccess Prasad Bezavada "+(2/0));
    } catch (Exception e){
        // doing nothing is ok for your intended behaviour
    }
}
} 

Upvotes: 1

Thirupathi Thangavel
Thirupathi Thangavel

Reputation: 2465

Try this.

java Test 2> /dev/null
if [ $? -eq 0 ]
then echo "1"
else echo "0"
fi

Upvotes: 2

Related Questions