11

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

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158

1 Answers1

5

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • The function you linked is not a great example, since it only throws unchecked exceptions as far as I can see, which do not have to be in the throw specification list. – Mooing Duck Aug 01 '12 at 20:43
  • Read the following sentence, then: "The thread represented by this thread is forced to complete whatever it is doing abnormally and to throw the Throwable object obj as an exception." – Marko Topolnik Aug 01 '12 at 20:45
  • Oh, missed that sentance, I was looking for Exception class names. Interesting find. – Mooing Duck Aug 01 '12 at 20:57