在做NtyTcp的时候,有一些,就想用c来实现一套try-catch异常处理子系统。
不讨论C语言本身为什么不加try-catch,每个开发的朋友对于这个问题,都能说出一大堆的理由。
其实我也是不太喜欢强行在c中加入一个try-catch。就像把try-catch的原理跟自己的体会写出来。
首先我们来看看,try-catch的使用情景。
try { throw Excep; } catch (Excep) { } finally { }
try{ } 块是可能有异常的抛出的地方。throw Excep
catch (Excep) { } 是 捕获相应抛出异常的地方。
finally { } 是不论什么情形下,都是需要执行的代码块。
如果实现一套如此机制,有何实现的基础依赖。那就是setjmp与longjmp
讲到setjmp与longjmp,也是更说明一下
#include <setjmp.h> #include <stdio.h> jmp_buf env; int count = 0; void sub_func(int idx) { printf("sub_func --> idx:%d\n", idx); longjmp(env, idx); } int main(int argc, char *argv[]) { int idx = 0; if ((count = setjmp(env)) == 0) { printf("count:%d\n", count); sub_func(++idx); } else if (count == 1) { printf("count:%d\n", count); } { printf("other count\n"); } return 0; }
先来定义个
全局的jmp_buf env; 用来保存跳转的上下文。
int count = 0; 用来保存跳转返回值的。有点绕口,就是记录setjmp返回值的。
看到这里也许对setjmp与longjmp有点理解。再换个马甲,相信更有体会。
#include <setjmp.h> #include <stdio.h> jmp_buf env; int count = 0; #define Try if ((count = setjmp(env)) == 0) #define Catch(e) else if (count == (e)) #define Finally ; #define Throw(idx) longjmp(env, (idx)) void sub_func(int idx) { printf("sub_func --> idx:%d\n", idx); Throw(idx); } int main(int argc, char *argv[]) { int idx = 0; Try { printf("count:%d\n", count); sub_func(++idx); } Catch(1) { printf("count:%d\n", count); } Finally { printf("other count\n"); } return 0; }
try-catch就已经初具雏形了。这样只是基本实现,还有三个问题没有解决。
如何保证线程安全。
如何解决try-catch 嵌套。
如何避免,在不加try的代码块直接Throw。
如何保证线程安全。
使用线程的私有数据 pthread_key_t ,每一个线程都有一个try-catch的上下文环境。
如何解决try-catch嵌套的问题
使用一个栈式数据结构,每次try的时候压栈,每次throw的时候 出栈。
如何避免,在不加try的代码块直接Throw,
这个问题就比较好理解。既然每次try需要压栈,如果不加try,所以栈里面没有数据。在Throw之前先查看栈里面有没有数据。
那现在问题又来了,在pthread_key_t 与 链式栈如何结合? 先看如下结构体,也许会有新的认识,结构体里面有一个prev的域。
这样就能跟pthread_key_t 来结合,每次讲结构体指针保存在pthread_key_t中,获取完之后,拿到prev的值。
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;
下面把整个实现代码都贴出来,大家也可以去我的github上面star,fork
/* * author : wangbojing * email : 1989wangbojing@163.com * github : https://github.com/wangbojing */ #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"); }
原文地址:http://blog.51cto.com/wangbojing/2120520