Skip to content

Commit

Permalink
✨ ADD 异常捕捉机制
Browse files Browse the repository at this point in the history
  • Loading branch information
sunwu51 committed Dec 7, 2024
1 parent 5ae49ee commit 075d5e2
Show file tree
Hide file tree
Showing 8 changed files with 1,009 additions and 0 deletions.
37 changes: 37 additions & 0 deletions 24.12/Demo.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <jni.h>
#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>

jmp_buf global_exception;
struct ErrorContext {
int code;
char msg[256];
};

void signal_handler(int signum) {
longjmp(global_exception, signum);
}
JNIEXPORT jint JNICALL Java_Demo_divide
(JNIEnv *env, jclass clz, jint a, jint b) {
signal(SIGSEGV, signal_handler);
struct ErrorContext ctx = {0};
// 设置异常捕获点
int exception = setjmp(global_exception);
if (exception == 0) {
int *p = NULL;
*p = 10;
return 1;
} else {
// 异常处理
ctx.code = exception;
snprintf(ctx.msg, sizeof(ctx.msg),
"Caught signal: %d", exception);

// 记录日志
fprintf(stderr, "Error: %s\n", ctx.msg);
return 0;
}
}
11 changes: 11 additions & 0 deletions 24.12/Demo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include <jni.h>
#include <stdexcept>
extern "C" JNIEXPORT jint JNICALL Java_Demo_divide
(JNIEnv *env, jclass clz, jint a, jint b) {
try {
return a /b;
} catch (const std::runtime_error &e) {
env->ThrowNew(env->FindClass("java/lang/ArithmeticException"), e.what());
return 0;
}
}
21 changes: 21 additions & 0 deletions 24.12/Demo.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions 24.12/Demo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class Demo {
public static native int divide(int a, int b);
public static native String toLowcase(String str);
static {
System.load("C:\\Users\\sunwu\\Desktop\\base\\gateway\\notebook\\24.12\\demo\\target\\release\\demo.dll");

// System.load("C:\\Users\\sunwu\\Desktop\\base\\gateway\\notebook\\24.12\\libDemo.dll");
}
public static void main(String[] args) throws Exception{
System.out.println(toLowcase("ABC"));
// try {
// Thread thread = new Thread(()-> {
// System.out.println(divide(10, 2));
// System.out.println(divide(10, 0));
// });
// thread.start();
// } catch (Throwable t) {
// System.out.println("Error " + t);
// }
// Thread.sleep(10000L);
// System.out.println("finish main");
}
}
294 changes: 294 additions & 0 deletions 24.12/demo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 075d5e2

Please sign in to comment.