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.)

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top