java.lang.NullPointerException and return code - java

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.");
}
}

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);
}
}

the return code is set by the exit method of System: by the way if, for instance, You want to return -1 in case of exception you can do as follow: in Your Main class you have to catch all throwable (so you will handle all possible case). here is an example
public static void main(String[] args) {
try { YOUR CODE
} catch(throwable t){
System.exit(-1);
}
System.exit(0);
}
the code show You how return -1 in case of exception and 0 in case of success.

Related

Why would Java skip lines of code after method failure?

I've seen this behavior a few times lately. In the code below, why would execution jump to the finally block immediately after executing method2? I know method2 failed in some way, but I do know that neither method3 nor method4 are executed, instead jumping to method 5 in the finally block
try {
method1();
method2(); // fails
method3(); // not executed
} catch(Exception e) {
method4(); // not executed
} finally {
method5();
}
Hopefully you're clear on why method3() is not executing.
A possible reason that method4() would not execute is that method is throwing a Throwable that is not a subclass of Exception - most likely some kind of Error.
It is because the exception being thrown is not being caught by the type "Exception"
For example, an out of memory error.
public static void main(String[] args) {
try {
method1();
method2(); // fails
method3(); // not executed
} catch(Exception e) {
method4(); // not executed
} finally {
method5();
}
}
private static void method5() {
System.out.println("Done");
}
private static void method4() {
System.out.println("Hit");
}
private static void method3() {
}
private static void method2() {
throw new OutOfMemoryError();
}
private static void method1() {
}
You can catch error types by try {} catch (Throwable t) { }

Throwing exception without " throws " for any type of exception

I want to throw an exception (any type) in Java, but the restriction is that i can't add " throws Exception " to my main method. So i tried this:
import java.io.IOException;
class Util
{
#SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Util.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void met() {
Util.throwException(new IOException("This is an exception!"));
}
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
This code works, but when i am trying to catch an "IOException", for examle, in try-catch block, it doesnt compile. The compiler tells me that IOException is never thrown. It works only for exceptions that extend RuntimeException. Is there a way to solve this?
Added:
import java.io.IOException;
class Util
{
#SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Util.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void met() { // this method's signature can't be changed
Util.throwException(new IOException("This is an exception!"));
}
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (IOException e) { // can't be changed and it does not compile right now
System.out.println(e.getMessage());
}
}
}
The simple answer: you can't.
The more complex answer: you can't, and you really shouldn't look to do this. The main reason being, if your code can catch exceptions that it's not advertised to, then that leads to inconsistency and bugs.
Above all, that code block isn't meant to catch anything other than an IOException; that is, the code is only meant to recover on something going haywire with IO. If I were to try and catch anything else, then that would imply that the code knows how to recover from that scenario, which is very much not the case.
As an aside, any children of IOException will be caught by that block, so you don't have to worry about catching FileNotFoundExecption, since that will handle it.
This is awful coding, and I feel dirty just writing it...
Instead of catch-ing the IOException directly, you can check that the caught Exception is an IOException.
public class Test
{
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (Exception e) {
if (e instanceof IOException) {
System.out.println(e.getMessage());
}
}
}
}

Java methods don't always need to declare throwing checked exceptions [duplicate]

I would expect the following code to raise a compile-time error on throw t;, because main is not declared to throw Throwable, but it compiles successfully (in Java 1.7.0_45), and produces the output you would expect it to if that compile-time error was fixed.
public class Test {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
}
It also compiles if Throwable is changed to Exception.
This does not compile, as expected:
public class Test {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch(Throwable t) {
Throwable t2 = t;
System.out.println("Caught "+t2);
throw t2;
}
}
}
This compiles:
public class Test {
public static void main(String[] args) {
try {
throwsRuntimeException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
public static void throwsRuntimeException() {
throw new NullPointerException();
}
}
This does not:
public class Test {
public static void main(String[] args) {
try {
throwsCheckedException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
public static void throwsCheckedException() {
throw new java.io.IOException();
}
}
This compiles as well:
public class Test {
public static void main(String[] args) throws java.io.IOException {
try {
throwsIOException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
public static void throwsIOException() throws java.io.IOException {
throw new java.io.IOException();
}
}
A more complex example - the checked exception is caught by an outer catch block, instead of being declared to be thrown. This compiles:
public class Test {
public static void main(String[] args) {
try {
try {
throwsIOException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
} catch(java.io.IOException e) {
System.out.println("Caught IOException (outer block)");
}
}
public static void throwsIOException() throws java.io.IOException {
throw new java.io.IOException();
}
}
So there seems to be a special case to allow rethrowing exceptions when the compiler can determine that the caught exception is always legal to re-throw. Is this correct? Where is this specified in the JLS? Are there any other obscure corner-cases like this?
This is covered by JLS 11.2.2 (emphasis mine):
A throw statement whose thrown expression is a final or effectively final exception parameter of a catch clause C can throw an exception class E iff:
E is an exception class that the try block of the try statement which declares C can throw; and
E is assignment compatible with any of C's catchable exception classes; and
(...)
In other words, E, the type referenced in the doc, is the type that can be thrown, not the type of the catch clause parameter that catches it (the catchable exception class). It just has to be assignment compatible to the catch clause parameter, but the parameter's type is not used in analysis.
This is why the go out of their way to say a final or effectively final exception parameter--if t in your example were reassigned, the analysis would go out the window.
Because the compiler is smart enough to know that a checked exception can not be thrown from the try block, and the caught Throwable is thus not a checked exception that must be declared.
Note that this is true since Java 7, if I'm not mistaken.
When you catch Throwable or Exception and the variable is effectively final you can rethrow the same variable and the compiler will know which checked exceptions you could have thrown in the try {} catch block.

Java exception specification for the main method

Do we not need exception specification for the main method in a Java program. For example, the following code works exactly the same without specifying "throws Xcept" for the main method.
class Xcept extends Exception {
public Xcept(){
}
public Xcept(String msg){
super(msg);
}
}
public class MyException {
public void f() throws Xcept {
System.out.println("Exception from f()");
throw new Xcept("Simple Exception");
}
public static void main(String[] args) throws Xcept {
MyException sed = new MyException();
try {
sed.f();
} catch(Xcept e) {
e.printStackTrace();
}
finally {
System.out.println("Reached here");
}
}
}
I read that java enforces this, but I don't get a compile time error if I exclude this specification for the main method.
That's because Xcept will never be thrown out of your main method, as you actually catch it there... The sed.f() call may result in an Xcept being thrown, but it's caught and handled.

Invorking fillInStackTrace method after invoked printStackTrace method

Blow is a example copied from Think in Java 4 edition
public class Rethrowing {
public static void f() throws Exception {
System.out.println("originating the exception in f()");
throw new Exception("thrown from f()");
}
public static void h() throws Exception {
try {
f();
} catch (Exception e) {
System.out.println("Inside h(),e.printStackTrace()");
e.printStackTrace(System.out); //first print line throw (Exception) e.fillInStackTrace();
}
}
public static void main(String[] args) {
try {
h();
} catch (Exception e) {
System.out.println("main: printStackTrace()");
e.printStackTrace(System.out);
}
}
}
Output:
originating the exception in f()
Inside h(),e.printStackTrace()
java.lang.Exception: thrown from f()
at Rethrowing.f(Rethrowing.java:20)
at Rethrowing.h(Rethrowing.java:25)
at Rethrowing.main(Rethrowing.java:35)
main: printStackTrace()
java.lang.Exception: thrown from f()
at Rethrowing.f(Rethrowing.java:20)
at Rethrowing.h(Rethrowing.java:25)
at Rethrowing.main(Rethrowing.java:35)
When comment //first print line
Output:
originating the exception in f()
Inside h(),e.printStackTrace()
main: printStackTrace()
java.lang.Exception: thrown from f()
at Rethrowing.h(Rethrowing.java:29)
at Rethrowing.main(Rethrowing.java:35)
My question is why i first invoke e.printStackTrace(printOut out ) method before the fillInStackTrace mehod, and then the fillInStackTrace seems not available. Any one can do me a faver, thanks in advance.
user917879, When you call e.fillInStackTrace(); it resets the StackTrace. So, to print the current StackTrace - before it is get reset - you need to invoke the e.printStackTrace(printOut out ) first.

Categories