Try Catch组件实现
先说明try catch组件使用setjump和longjump实现
setjump longjump语法
Int setjmp(jmp_buf env);
返回值:若直接调用则返回0,若从longjmp调用返回则返回非0值的longjmp中的val值
Void longjmp(jmp_buf env,int val);
调用此函数则返回到语句setjmp所在的地方,其中env 就是setjmp中的 env,而val 则是使setjmp的返回值变为val。
当检查到一个错误时,则以两个参数调用longjmp函数,第一个就是在调用setjmp时所用的env,第二个参数是具有非0值val,它将成为从setjmp处返回的值。使用第二个参数的原因是对于一个setjmp可以有多个longjmp。
jmp_buf env;环境
setjump(env)设置回跳点,返回longjump(env,out)传的参数out,配套使用,longjump可穿越函数跳转
jmp_buf env;
int c = setjump(env);
longjump(env,3);
这里longjump后就会跳回setjump这一行,并且setjump会返回3,也就是c = 3。
int count = 0;
jmp_buf env;
void a(int indx)
{
longjump(env,indx);
}
int main()
{
int idx = 0;
count = setjump(env);
if(count == 0)
{
a(env,idx++);
}
else if (count == 1)
{
a(env,idx++);
}
else
{
printf("ok");
}
return 0;
}
如上,函数a会调回开头setjump处,如果是这样a调用多次,a又没有返回(a运行到longjump处进入了,没返回),a的栈会不会还存在,存在的话如果有无数个a,会不会发生栈溢出。
答案是不会,因为a在进入longjump后,其栈指针直接失效,a的栈直接失效,在setjump函数所在函数block中被覆盖,所以a的多次调用不会发生栈溢出。
setjump 与 longjump本身是线程安全的
setjump longjump与try catch的关系
先来个 代码:
try{ //setjump to catch
throw(); // longjump(para)
} catch (para) {
} finally () {
}
来看对应的:
int count = 0;
jmp_buf env;
void a(int indx)
{
longjump(env,indx);
}
int main()
{
int idx = 0;
count = setjump(env);
if(count == 0) // try()
{
a(env,idx++); //throw(1)
}
else if (count == 1)//catch(1)
{
a(env,idx++);//throw(2)
}
//finally
{
printf("ok");
}
return 0;
}
再上代码,直接用宏定义try catch throw finally:
#include <stdio.h>
#include <setjmp.h>
typedef struct _tagExcepSign {
jmp_buf _stackinfo;
int _exceptype;
} tagExcepSign;
#define ExcepType(ExcepSign) ((ExcepSign)._exceptype)
#define Try(ExcepSign) if (((ExcepSign)._exceptype = setjmp((ExcepSign)._stackinfo)) == 0)
#define Catch(ExcepSign, ExcepType) else if ((ExcepSign)._exceptype == ExcepType)
#define Finally else
#define Throw(ExcepSign, ExcepType) longjmp((ExcepSign)._stackinfo, ExcepType)
void ExceptionTest(int expType) {
tagExcepSign ex;
expType = expType < 0 ? -expType : expType;
Try (ex) {
if (expType > 0) {
Throw(ex, expType);
} else {
printf("no exception\n");
}
} Catch (ex, 1) {
printf("no exception 1\n");
} Catch (ex, 2) {
printf("no exception 2\n");
} Finally {
printf("other exp\n");
}
}
int main() {
ExceptionTest(0);
ExceptionTest(1);
ExceptionTest(2);
ExceptionTest(3);
}
现在有个新问题,try catch嵌套怎么办。
以下三个问题需要实现:
- 多个ex依次入栈,每次只处理栈顶ex,解决嵌套问题
- 需要在throw的时候抛出异常发生的位置(文件、行号、函数名),可使用编译器自带的宏:
__FILE__ __LINE__ __func__
- 虽然函数setjump和longjump是线程安全的,但ex变量在多线程时被共用,那ex就成为临界变量,如何保证ex的线程安全
以下代码实现以上功能:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <pthread.h>
#include <setjmp.h>
#define ntyThreadData pthread_key_t
#define ntyThreadDataSet(key, value) pthread_setspecific((key), (value))
#define ntyThreadDataGet(key) pthread_getspecific((key))
#define ntyThreadDataCreate(key) pthread_key_create(&(key), NULL)
#define EXCEPTIN_MESSAGE_LENGTH 512
typedef struct _ntyException {
const char *name;
} ntyException;
ntyException SQLException = {"SQLException"};
ntyException TimeoutException = {"TimeoutException"};
ntyThreadData ExceptionStack;
typedef struct _ntyExceptionFrame {
jmp_buf env;
int line;
const char *func;
const char *file;
ntyException *exception;
struct _ntyExceptionFrame *prev;
char message[EXCEPTIN_MESSAGE_LENGTH+1];
} ntyExceptionFrame;
#define ntyExceptionPopStack \
ntyThreadDataSet(ExceptionStack, ((ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack))->prev)
#define ReThrow ntyExceptionThrow(frame.exception, frame.func, frame.file, frame.line, NULL)
#define Throw(e, cause, ...) ntyExceptionThrow(&(e), __func__, __FILE__, __LINE__, cause, ##__VA_ARGS__, NULL)
enum {
ExceptionEntered = 0,
ExceptionThrown,
ExceptionHandled,
ExceptionFinalized
};
#define Try do { \
volatile int Exception_flag; \
ntyExceptionFrame frame; \
frame.message[0] = 0; \
frame.prev = (ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack); \
ntyThreadDataSet(ExceptionStack, &frame); \
Exception_flag = setjmp(frame.env); \
if (Exception_flag == ExceptionEntered) {
#define Catch(e) \
if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \
} else if (frame.exception == &(e)) { \
Exception_flag = ExceptionHandled;
#define Finally \
if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \
} { \
if (Exception_flag == ExceptionEntered) \
Exception_flag = ExceptionFinalized;
#define EndTry \
if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \
} if (Exception_flag == ExceptionThrown) ReThrow; \
} while (0)
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
static void init_once(void) {
ntyThreadDataCreate(ExceptionStack);
}
void ntyExceptionInit(void) {
pthread_once(&once_control, init_once);
}
void ntyExceptionThrow(ntyException *excep, const char *func, const char *file, int line, const char *cause, ...) {
va_list ap;
ntyExceptionFrame *frame = (ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack);
if (frame) {
frame->exception = excep;
frame->func = func;
frame->file = file;
frame->line = line;
if (cause) {
va_start(ap, cause);
vsnprintf(frame->message, EXCEPTIN_MESSAGE_LENGTH, cause, ap);
va_end(ap);
}
ntyExceptionPopStack;
longjmp(frame->env, ExceptionThrown);
} else if (cause) {
char message[EXCEPTIN_MESSAGE_LENGTH+1];
va_start(ap, cause);
vsnprintf(message, EXCEPTIN_MESSAGE_LENGTH, cause, ap);
va_end(ap);
printf("%s: %s\n raised in %s at %s:%d\n", excep->name, message, func ? func : "?", file ? file : "?", line);
} else {
printf("%s: %p\n raised in %s at %s:%d\n", excep->name, excep, func ? func : "?", file ? file : "?", line);
}
}
/* ** **** ******** **************** debug **************** ******** **** ** */
ntyException A = {"AException"};
ntyException B = {"BException"};
ntyException C = {"CException"};
ntyException D = {"DException"};
void *thread(void *args) {
pthread_t selfid = pthread_self();
Try {
Throw(A, "A");
} Catch (A) {
printf("catch A : %ld\n", selfid);
} EndTry;
Try {
Throw(B, "B");
} Catch (B) {
printf("catch B : %ld\n", selfid);
} EndTry;
Try {
Throw(C, "C");
} Catch (C) {
printf("catch C : %ld\n", selfid);
} EndTry;
Try {
Throw(D, "D");
} Catch (D) {
printf("catch D : %ld\n", selfid);
} EndTry;
Try {
Throw(A, "A Again");
Throw(B, "B Again");
Throw(C, "C Again");
Throw(D, "D Again");
} Catch (A) {
printf("catch A again : %ld\n", selfid);
} Catch (B) {
printf("catch B again : %ld\n", selfid);
} Catch (C) {
printf("catch C again : %ld\n", selfid);
} Catch (D) {
printf("catch B again : %ld\n", selfid);
} EndTry;
}
#define THREADS 50
int main(void) {
ntyExceptionInit();
Throw(D, NULL);
Throw(C, "null C");
printf("\n\n=> Test1: Try-Catch\n");
Try {
Try {
Throw(B, "recall B");
} Catch (B) {
printf("recall B \n");
} EndTry;
Throw(A, NULL);
} Catch(A) {
printf("\tResult: Ok\n");
} EndTry;
printf("=> Test1: Ok\n\n");
printf("=> Test2: Test Thread-safeness\n");
#if 1
int i = 0;
pthread_t threads[THREADS];
for (i = 0;i < THREADS;i ++) {
pthread_create(&threads[i], NULL, thread, NULL);
}
for (i = 0;i < THREADS;i ++) {
pthread_join(threads[i], NULL);
}
#endif
printf("=> Test2: Ok\n\n");
}