设为首页 加入收藏

TOP

用c语言模拟c++的异常处理机制(三)
2012-11-01 09:13:51 来源: 作者: 【 】 浏览:889
Tags:语言 模拟 异常 处理 机制

   
    }while(0)
   
    extern void list_add_before(list_head *node, list_head *pos);
   
    extern void list_add_after(list_head *node, list_head *pos);
   
    extern void list_del(list_head *node);
   
    #endif
   
    #include “list.h”
   
    void list_add_before(list_head *node, list_head *pos)
   
    {
   
    node->prev = pos->prev;
   
    node->next = pos;
   
    pos->prev->next = node;
   
    pos->prev = node;
   
    }
   
    void list_add_after(list_head *node, list_head *pos)
   
    {
   
    node->prev = pos;
   
    node->next = pos->next;
   
    pos->next->prev = node;
   
    pos->next = node;
   
    }
   
    void list_del(list_head *node)
   
    {
   
    node->prev->next = node->next;
   
    node->next->prev = node->prev;
   
    }
   
    #ifndef EXC_H
   
    #define EXC_H
   
    char err = -1;
   
    static char isJumpListInit = 0;
   
    //jmp_buf jump_buffer;
   
    typedef struct JumpBufListTag
   
    {
   
    struct list_head_tag list;
   
    jmp_buf jump_buffer;
   
    }JumpBufList, *JumpBufListPtr;
   
    JumpBufList jumplist = {NULL, NULL};
   
    JumpBufListPtr head = &jumplist;
   
    JumpBufListPtr cur = &jumplist;
   
    int SetCurJump(void)
   
    {
   
    JumpBufListPtr newPtr = (JumpBufList*)calloc(sizeof(JumpBufList));
   
    if (!isJumpListInit)
   
    {
   
    init_list_head(&head->list);
   
    isJumpListInit = 1;
   
    }
   
    list_add_after(&newPtr->list, &head->list);
   
    cur = newPtr;
   
    return 0;
   
    }
   
    void JumpCurLong(void)
   
    {
   
    longjmp(cur->jump_buffer, 1);
   
    }
   
    void DestoryCurJumpEnv( void )
   
    {
   
    list_del(&cur->list);
   
    free(cur);
   
    cur = head->list.next;
   
    }
   
    #define try SetCurJump();if(setjmp(cur->jump_buffer) == 0)
   
    #define catch(N) DestoryCurJumpEnv();if(N>=0)
   
    #define throw(N) err=N;JumpCurLong();
   
    #endif
   
    这边,List.h和list.c摘抄自linux内核代码。
   
    使用demo代码:
   
    void h()
   
    {
   
    throw(7);
   
    }
   
    void e()
   
    {
   
    h();
   
    }
   
    void g(void)
   
    {
   
    try
   
    {
   
    e();
   
    printf(“g()3”);
   
    }
   
    catch(err)
   
    {
   
    throw(err);
   
    }
   
    }
   
    int main()
   
    {
   
    try
   
    {
   
    g();
   
    }
   
    catch(err)
   
    {
   
    printf(“%d”, err);
   
    }
   
    return 0;
   
    }
   
    这样,就可以实现一个简易版本的用c语言模拟c++的错误处理异常的机制了。

      

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言中强制类型转换总结 下一篇C语言return的使用

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: