JNI - Exception Handling

.java file:

class CatchThrow{
	private native void doit()
		throws IllegalArgumentException;
	private void callback() throws NullPointerException{
		throw new NullPointerException("CathThrow.callback");	
	}
	public static void main(String args[]){
		CatchThrow c = new CatchThrow();
		try {
			c.doit();
		} catch (Exception e){
			System.out.println("In Java:\n\t" + e);	
		}
	}
	static {
		System.loadLibrary("CatchThrow");
	}

}

.c file:

#include <jni.h>
#include <stdio.h>
#include "CatchThrow.h"
JNIEXPORT void JNICALL <span style="color:#000099;">Java_CatchThrow_doit //do it.</span>
  (JNIEnv *env, jobject obj){
	jthrowable exc;
	jclass cls = (*env)->GetObjectClass(env,obj);
	jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "()V");
	if (mid == NULL) return;
	<span style="color:#000099;">(*env)->CallVoidMethod(env, obj, mid);//Invoke callback</span>
	exc = (*env)->ExceptionOccurred(env);
	if (exc){
		jclass newExcCls;
		<span style="color:#009900;">(*env)->ExceptionDescribe(env);//This stmt describes the stack trace.</span>
		(*env)->ExceptionClear(env);
		newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
		if (newExcCls == NULL){
			return;
		}
		(*env)->ThrowNew(env, newExcCls, "thrown from C code");
	}

}

Result:

Exception in thread "main" java.lang.NullPointerException: CathThrow.callback
	at CatchThrow.callback(CatchThrow.java:5)
	at CatchThrow.doit(Native Method)
	at CatchThrow.main(CatchThrow.java:10)
In Java:
	java.lang.IllegalArgumentException: thrown from C code


In JNI, an exception does not immediately disrupt the native method execution. This is different from Java(JVM automatically transfer the control flow to the nearest try/catch).
JNI need to explicitly implement the control flow after an exception has occurred.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值