Files
ndk-samples/exceptions
Dan Albert aa52693f43 Remove obsolete, duplicate, and useless docs.
License text, setup instructions, and support info do not need to be
duplicated into every README, since they're already in the top-level
README. They were originally in each sample because the samples used to
each be separate Android Studio projects with different requirements
that could be checkout out independently in Android Studio. This is no
longer the case.

Most of the docs also included text along the lines of "This sample uses
the new Android Studio with CMake support", which hasn't been new since
2015, so doesn't really need to be said.

The prerequisites were mostly not true. Android Studio is not required
for any of this. Cloning the repo and running `./gradlew build` is
sufficient to build all the samples. They also were not being kept
up-to-date at all, since they mostly said "Android Studio 2.2 or newer",
which was definitely not true. I'm not what the oldest version of
Android Studio that will work here is, but I don't actually test
anything but the latest so claiming anything otherwise is just
misleading.

I haven't pruned or edited any of the real content of the docs. I'm sure
there are plenty of edits to be made there and a lot of expansion to do,
but those changes will be less mechanical and will happen separately.
2025-09-25 20:41:14 +00:00
..
2022-12-13 11:14:02 -06:00
2022-12-13 11:14:02 -06:00

Exceptions

This Android sample shows how to handle exceptions across the JNI boundary.

Handling native exceptions

Native exceptions can be caught in JNI methods and re-thrown in the JVM. Because uncaught native exceptions will cause your app to crash, we recommend catching all exceptions as a fail-safe. You may also want to catch instances of std::exception or your own exception interface:

extern "C" JNIEXPORT void JNICALL
Java_com_example_exceptions_MainActivity_throwsException(JNIEnv* env,
                                                         jobject /* this */) {
  try {
    might_throw();
  } catch (std::exception& e) {
    jniThrowRuntimeException(env, e.what());
  } catch (...) {
    jniThrowRuntimeException(env, "Catch-all");
  }
}

Then, you can do the same in your Java/Kotlin code:

    try {
        jniMethodThatMightThrow();
    } catch (e: java.lang.RuntimeException) {
        // Handle exception
    }

The hard part here is using the JNI API to throw an exception in the JVM. That is, implementing jniThrowRuntimeException. We recommend referring to JNIHelp.h and JNIHelp.c in the Android platform's libnativehelper, from which exception_helper.h and exception_helper.cpp are adapted.

Screenshot

screenshot