简体   繁体   English

在Android NDK C ++代码中捕获异常

[英]Catch exception in Android NDK C++ code

I am trying to catch an error in native C++ code on Android. 我正在尝试在Android上的本机C ++代码中捕获错误。 According to the docs FindClass returns NULL when class name cannot be find. 根据文档,当找不到类名时,FindClass返回NULL。 But I got FATAL EXCEPTION: main java.lang.NoClassDefFoundError: fake/class and execution never reaches the if statement. 但是我得到了FATAL EXCEPTION: main java.lang.NoClassDefFoundError: fake/class ,执行从未达到if语句。

#include <string.h>
#include <jni.h>

extern "C"
void Java_com_example_MainActivity_testError(JNIEnv *env, jobject) {
    jclass clazz = env->FindClass("fake/class");
    // never gets here
    if (clazz == NULL) {
        return;
    }
}

Also this exception skips the try-catch block and crashes the app. 此外,此异常还会跳过try-catch块并使应用程序崩溃。 My Java code: 我的Java代码:

static {
    System.loadLibrary("native-lib");
}

public native void testError();

...
try {
    testError();
} catch (Exception e) {
    // exception never get cought
}

Also I use cppFlags '-fexceptions' . 我也使用cppFlags '-fexceptions' Is there a proper way to catch this exception or recover from it so the app does not crash? 是否有适当的方法来捕获此异常或从中恢复以确保应用程序不会崩溃?

First, to prevent native code from crashing on FindClass, etc. you have to use this code after every JNI call: 首先,为防止本机代码在FindClass等上崩溃,您必须在每次JNI调用之后使用以下代码:

bool checkExc(JNIEnv *env) {
    if (env->ExceptionCheck()) {
        env->ExceptionDescribe(); // writes to logcat
        env->ExceptionClear();
        return true;
    }
    return false;
}

Actually, ExceptionClear() stops the crash. 实际上,ExceptionClear()可以停止崩溃。 I have found the code on this answer https://stackoverflow.com/a/33777516/2424777 我在此答案上找到了代码https://stackoverflow.com/a/33777516/2424777

Second, to be sure to catch all crashes from native code, you have to use this try-catch. 其次,要确保从本机代码捕获所有崩溃,您必须使用此try-catch。 Credits @Richard Critten Also use it on all native function calls: 积分@Richard Critten也可以在所有本机函数调用上使用它:

static {
    try {
        System.loadLibrary("native-lib");
    } catch (Error | Exception ignore) { }
}

And cppFlags '-fexceptions' has nothing to do it so you can remove it. 而且cppFlags'-fexceptions'与它无关,因此您可以将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM