diff --git a/extension/android/jni/jni_helper.cpp b/extension/android/jni/jni_helper.cpp index b92856bacb2..6491524c7ac 100644 --- a/extension/android/jni/jni_helper.cpp +++ b/extension/android/jni/jni_helper.cpp @@ -13,10 +13,13 @@ namespace executorch::jni_helper { void throwExecutorchException(uint32_t errorCode, const std::string& details) { // Get the current JNI environment auto env = facebook::jni::Environment::current(); + if (!env) { + return; + } - // Find the Java ExecutorchRuntimeException class - static auto exceptionClass = facebook::jni::findClassLocal( - "org/pytorch/executorch/ExecutorchRuntimeException"); + // stable/global class ref — safe to cache + static const auto exceptionClass = + JExecutorchRuntimeException::javaClassStatic(); // Find the static factory method: makeExecutorchException(int, String) static auto makeExceptionMethod = diff --git a/extension/android/jni/jni_helper.h b/extension/android/jni/jni_helper.h index 996d75581d3..898c1619d9c 100644 --- a/extension/android/jni/jni_helper.h +++ b/extension/android/jni/jni_helper.h @@ -23,4 +23,11 @@ namespace executorch::jni_helper { */ void throwExecutorchException(uint32_t errorCode, const std::string& details); +// Define the JavaClass wrapper +struct JExecutorchRuntimeException + : public facebook::jni::JavaClass { + static constexpr auto kJavaDescriptor = + "Lorg/pytorch/executorch/ExecutorchRuntimeException;"; +}; + } // namespace executorch::jni_helper