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


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.

链接地址: http://www.djcxy.com/p/5952.html

上一篇: SAXException:尾部不允许使用内容

下一篇: Java检查异常不在函数的throw规范中?