多此一舉, C實現 try-catch


在做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就已經初具雛形了。這樣只是基本實現,還有三個問題沒有解決。

  1.   如何保證線程安全。

  2.  如何解決try-catch 嵌套。

  3.  如何避免,在不加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 : [email protected] 
 * 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");

}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章