以下是java代码,旁边是c代码:
package Package;
public class CatchThrow {
private native void doit() throws IllegalArgumentException;
private void callBack() throws NullPointerException {
System.out.println("In call-back !");
throw new NullPointerException("CatchThrow.callBack");
}
public static void main(String args[]) {
CatchThrow c = new CatchThrow();
try {
c.doit();
} catch(Exception exc) {
System.out.println("\nIn Java : \n\t" + exc);
}
}
static {
System.loadLibrary("CatchThrow");
}
}
C代码:
#include "stdio.h"
#include "Package_CatchThrow.h"
void Java_Package_CatchThrow_doit
(JNIEnv *env, jobject obj) {
jthrowable exc;
jclass cls = (*env)->GetObjectClass(env,obj);
jmethodID mid = (*env)->GetMethodID(env,cls,"callBack","()V");
if(mid == NULL) {
return;
}
(*env)->CallVoidMethod(env,obj,mid); // call the java method that throws NullPointerException
printf("After the call to Call-Back !");
exc = (*env)->ExceptionOccurred(env);
if(exc) {
jclass newExcCls;
printf("\n");
//(*env)->ExceptionDescribe(env); ----> NOTE THE COMMENTED STATEMENT
//(*env)->ExceptionClear(env); -----> NOTE THE COMMENTED STATEMENT
newExcCls = (*env)->FindClass(env,"java/lang/IllegalArgumentException");
if(newExcCls == NULL) {
return;
}
(*env)->ThrowNew(env,newExcCls,"thrown from c code");
}
}
当我构建并运行上述程序时,我得到以下输出:
In call-back !
After the call to Call-Back !
In Java :
java.lang.IllegalArgumentException: thrown from c code
从输出: C 代码调用 java 函数callBack。那里打印了第一条语句。在调用返回调用旁边的语句后,即After the call to Call-Back !
打印出来。但是throw new NullPointerException("CatchThrow.callBack");
java 函数callBack中的语句发生了什么?为什么它不打印异常?
但是如果我从陈述中删除评论
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
评论说,我得到了所需的输出:
In call-back !
After the call to Call-Back !
Exception in thread "main" java.lang.NullPointerException: CatchThrow.callBack
at Package.CatchThrow.callBack(CatchThrow.java:14)
at Package.CatchThrow.doit(Native Method)
at Package.CatchThrow.main(CatchThrow.java:20)
In Java :
java.lang.IllegalArgumentException: thrown from c code
这是为什么 ?
这两个语句的作用是什么?为什么在没有这两条语句的情况下不打印异常?