I’m running some java binary from bash like:
run_me.sh
$JAVA_HOME/bin/java -Djava.library.path=path1/libs/opencv/lib -jar path2/bin/application.jar echo "Exit code: "$?
but inside application I get java.lang.NullPointerException
, howewer return code is 0, but I need some non zero exit code to understand from bash that application failed.
What is the proper way to handle such cases?
Update:
Here is an exxample of ‘nested’ try catch blocks, when I throw exception in inner_package_class
return code is 0. So what is the proper way to get exception from inner_package_class.method1()?
public static void main(String[] args) { try { inner_package_class.method1(); System.out.printf("After inner method!n"); } catch (Throwable t) { System.exit(1); } } public class inner_package_class { public static void method1() { System.out.printf("From inner method!n"); try { throw new Exception("Some exception 2."); } catch (Throwable t) { } } }
Update 1: This work as expected (return non zero exit code).
public class inner_package_class { public static void method1() throws Exception { System.out.printf("From inner method!n"); throw new Exception("Some exception 2."); } }
Advertisement
Answer
You can add a try-catch-block around your main method and use
System.exit(1)
when you catch a Throwable
public static void main(String[] args) { try { ... // your original code } catch (Throwable t) { // log the exception t.printStacktrace(); // or use your logging framework System.exit(1); } }