What happens when I throw a C++ exception from a native Java method?

前端 未结 5 1690
时光取名叫无心
时光取名叫无心 2020-12-08 07:22

Suppose I\'m embedding Sun\'s JVM in a C++ application. Through JNI I call a Java method (my own), which in turns calls a native method I implemented in a shared library.

5条回答
  •  青春惊慌失措
    2020-12-08 08:14

    I would label that as undefined behavior. Propagation of exceptions back to C code (that's what is running the JVM) is undefined behavior.

    On Windows, compilers have to use Microsoft's Structured Exception Handling to implement exceptions, so C++ exceptions will be "safely" caried through C code. However, that C code is not written with exceptions in mind, so you will get a crash if you're lucky, and inconsistent state and resource leaks if you aren't.

    On other platforms, well, I don't know, but it can't be any prettier. When I write JNI code, I wrap every C++ function in a try block: even if I don't throw, I still might get some of the standard exceptions (std::bad_alloc comes to mind, but others are possible too).

提交回复
热议问题