共有回帖数 0 个
- 〔exception handling〕C语言简单实现-20110322-pre-alpha-1
-
只看楼主
收藏
回复
-
我承认咱本来是学C++的,C没有try搞的咱有时候感觉不太爽
抽空撸了几个try/catch/throw宏,目前没什么大的bug
#include setjmp.h
int __cmacro_jmp_pos;
jmp_buf __cmacro_jmp_buf[128];
/* exception handling implementation for cmacro */
// *****************************************************************************
#define cmacro_try_begin()
{
int __jmp_ret;
int __try_catched = 0;
if((__jmp_ret = setjmp(__cmacro_jmp_buf[__cmacro_jmp_pos++])) == 0)
{
#define cmacro_try_catch(exception)
}
else if(__jmp_ret == (exception))
{
__cmacro_jmp_pos--;
__try_catched = 1;
#define cmacro_try_end()
}
else
{
fprintf(stderr, "unhandled exception(%d) at file %s, line %dn",
__jmp_ret,
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
if(!__try_catched) __cmacro_jmp_pos--;
}
#define cmacro_try_throw(exception)
{
if(__cmacro_jmp_pos 0)
{
longjmp(__cmacro_jmp_buf[__cmacro_jmp_pos - 1], exception);
}
else
{
fprintf(stderr, "unhandled exception(%d) at file %s, line %dn",
exception,
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
}
以下是一个简单的测试
#include stdio.h
int fvck456()
{
cmacro_try_throw(456);
return 0;
}
int fvck123()
{
cmacro_try_throw(123);
return 0;
}
int main()
{
cmacro_try_begin()
{
fvck123();
}
cmacro_try_catch(123)
{
printf("%sn", "exception 123");
cmacro_try_begin()
{
fvck456();
}
cmacro_try_catch(123)
{
printf("%sn", "exception 123");
}
cmacro_try_catch(456)
{
printf("%sn", "exception 456");
fvck123();
}
cmacro_try_end();
}
cmacro_try_end();
return 0;
}
楼主 2015-11-26 14:49 回复
Copyright © 2010~2015 直线网 版权所有,All Rights Reserved.沪ICP备10039589号
意见反馈 |
关于直线 |
版权声明 |
会员须知