jni异常,c++抛出异常,java捕获

来源:互联网 发布:大数据概念板块 编辑:程序博客网 时间:2024/05/05 19:18
public class MainActivity extends AppCompatActivity {    // Used to load the 'native-lib' library on application startup.    static {        System.loadLibrary("native-lib");    }    public native void doit() throws IllegalArgumentException;    public void callback() throws NullPointerException {        throw new NullPointerException("**********Throw**********");    }    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // Example of a call to a native method        //TextView tv = (TextView) findViewById(R.id.sample_text);        //tv.setText(stringFromJNI());        try {            doit();        }catch (Exception e){            System.out.println("In Java:\n\t" + e);        }    }}

在native-lib.cpp中,原本没有异常的情况下,不需要清除异常等行为

#include <jni.h>#include <string>#include <android/log.h>extern "C"voidJava_com_example_administrator_mytestjniexception_MainActivity_doit(JNIEnv* env,jobject obj) {    __android_log_print(ANDROID_LOG_INFO, "JNITag","start jni func doti");    jclass newExcCls;    newExcCls = env->FindClass("java/lang/IllegalArgumentException");    if (newExcCls == NULL) {        /* Unable to find the exception class, give up. */        __android_log_print(ANDROID_LOG_INFO, "JNITag","jni return");        return ;    }    env->ThrowNew(newExcCls, "***** thrown new exception from C code *****");    return ;}


输出日志



如果原本存在异常,需要先清除这个异常,再抛出新的异常

    if (exc) {        //对发生的异常进行描述        env->ExceptionDescribe();        //清除掉发生的异常        env->ExceptionClear();}





0 0