//java异常全类名
const
std::string CLS_JNIEXCEPTION =
"cn/wisenergy/pi/workflow/JNIException"
;
//在JNI中实现抛java异常
void
ThrowJNIException(JNIEnv *env,
const
std::string& errorMsg)
{
jclass e_cls = env->FindClass(CLS_JNIEXCEPTION.c_str());
if
(e_cls==NULL)
{
std::cerr <<
"find class:"
<< CLS_JNIEXCEPTION <<
" error!"
<< std::endl;
return
;
}
int
r = env->ThrowNew(e_cls,errorMsg.c_str());
std::cerr <<
"throw result:"
<< r << std::endl;
}
|
C++端,处理异常后,一定记得要return。否则程序会继续进行。也许在后面的代码中会有异常产生。强烈建议使用如下风格代码
cpp exception in JNI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
void
testException()
{
try
{
doSomeThing
//this line throws some exception.
}
catch
(std::exception & e)
{
std::string exceptionClass=
"java/lang/NullPointerException"
;
JNI::ThrowException(env,exceptionClass,e.what());
return
;
}
doOtherThing
//this line maybe throws some exception.
}
|