文章目录
1.finally是不管try和catch是否执行,finally都执行
2.跳转
goto :函数内部跳转,函数的栈里面
setjmp:设置标签位,提供来用的,第一次设置setjmp返回是0
longjmp:长跳,函数跳转,但是代码阅读性不好
3.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); //throw
}
int main(int argc, char *argv[]) {
int idx = 0;
count = setjmp(env);
if (count == 0) { //try
printf("count:%d\n", count);
sub_func(++idx);
} else if (count == 1) { //catch(1)
printf("count:%d\n", count);
sub_func(++idx);
} else if (count == 2) { //catch(2)
printf("count:%d\n", count);
sub_func(++idx);
} else if (count == 3) { //catch(3)
printf("count:%d\n", count);
sub_func(++idx);
} else {
printf("other count\n");
}
//finally
return 0;
}
4.try-catch组件第一次尝试
#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);
}
- 效果
5.try-catch嵌套(跟栈一样,底层内部捕捉处理完了,外部才开始处理)
- 备注:
哪个文件:__FILE__
哪个行号__LINE__
函数名:__func__
pthread_key_t有线程的私有空间,key是全局变量,但是线程1有一块空间,线程2有另外一块空间,每块线程的私有数据是不一样的
- 注意
①try-catch的setjmp/longjmp是线程安全的,但是结构体不是线程安全的
②每一个线程一个栈
- 方法:
单向链表实现栈,头插法