teaching machines

Convert a C++ Exception Into a Java Exception

June 17, 2014 by . Filed under madeup, public.

In Madeup, I needed an exception to propagate from C++ to Java to PHP. I was pretty certain the conventional exception mechanics wouldn’t support this, especially the leap from Java to PHP, but I think I’m wrong.

On the C++ side of the JNI bridge, I catch the exception and then throw it back to Java using the env parameter that all JNI C++ methods receive:

JNIEXPORT void JNICALL Java_my_package_MyClass_myMethod(JNIEnv *env, jclass) {
  try {
    // dangerous code
  } catch (std::exception e) {
    jclass java_exception_class = env->FindClass("my/package/MyExceptionClass");
    env->ThrowNew(java_exception_class, e.what());

On the Java side, the exception is like any other exception.

How do I hand it off to PHP? Well, somewhere in the past 15 years, a Java-PHP bridge has been written. Instead of invoking the JVM with a general system or exec command, there’s an API. One can even query for the last Java exception. This was too crazy for me. I settled for just having an exception jump from C++ to Java.


Leave a Reply

Your email address will not be published. Required fields are marked *