public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
public native void doit() throws IllegalArgumentException;
public void callback() throws NullPointerException {
throw new NullPointerException("**********Throw**********");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
//TextView tv = (TextView) findViewById(R.id.sample_text);
//tv.setText(stringFromJNI());
try {
doit();
}catch (Exception e){
System.out.println("In Java:\n\t" + e);
}
}
}
在native-lib.cpp中,原本没有异常的情况下,不需要清除异常等行为
#include <jni.h>
#include <string>
#include <android/log.h>
extern "C"
void
Java_com_example_administrator_mytestjniexception_MainActivity_doit(JNIEnv* env,jobject obj) {
__android_log_print(ANDROID_LOG_INFO, "JNITag","start jni func doti");
jclass newExcCls;
newExcCls = env->FindClass("java/lang/IllegalArgumentException");
if (newExcCls == NULL) {
/* Unable to find the exception class, give up. */
__android_log_print(ANDROID_LOG_INFO, "JNITag","jni return");
return ;
}
env->ThrowNew(newExcCls, "***** thrown new exception from C code *****");
return ;
}
如果原本存在异常,需要先清除这个异常,再抛出新的异常
if (exc) {
//对发生的异常进行描述
env->ExceptionDescribe();
//清除掉发生的异常
env->ExceptionClear();
}