Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java checked exception not in the function's throw specification?

Normally, the Java compiler confirms that all checked exceptions that are thrown are in the throw specification. Does anything special happen when a native function throws a java checked exception that was not in the functions throw specification list, or does is the throw specification list simply ignored at runtime?

C++

void function(JNIEnv * env, jclass jc) {
    jclass newExcCls = env->FindClass("java/lang/NullPointerException");
    env->ThrowNew(newExcCls, "ERROR");
}

Java

public class Tester {
    static {
        System.loadLibrary( "MyLibrary" );
    }        
    private static native void function();
    public static void main(String [ ] args) {
        try {
            function();
        } catch( Exception e ) { //is it caught? Or what happens?
            e.printStackTrace();
        }        
    }
}

(The C++ function name would probably be mangled. Also loadLibrary should be in a try catch. Don't care, I don't believe it's relevant to the problem. There's possibly other errors in the code, but they're probably not relevant either.)

like image 641
Mooing Duck Avatar asked Aug 01 '12 19:08

Mooing Duck


1 Answers

You don't even have to resort to native code to fool the checked exception mechanism. See the Javadoc on Thread.stop(Throwable). I was once left wondering for the entire day how my code threw an InterruptedException in the middle of code that did not declare it. I didn't even find the answer then, but now I know :)

Answering your immediate question: yes, the checked exception logic is a compiler-only feature and ignored at runtime.

like image 82
Marko Topolnik Avatar answered Oct 03 '22 15:10

Marko Topolnik