c_cpp 使用setjmp / longjmp的C中的异常

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用setjmp / longjmp的C中的异常相关的知识,希望对你有一定的参考价值。

/**
 * EXAMPLE 1: TRY/CATCH/THROW
*/

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>


#define TRY do{ jmp_buf env; if(!setjmp(env)) {
#define CATCH } else {
#define END_TRY } }while(0)
#define THROW longjmp(env, 1)

int main(int argc, char *argv[]) {

  TRY {
    printf("In TRY statement\n");
    THROW;
    printf("not reachable\n");
  }
  CATCH {
    printf("exception caught\n");
  }
  END_TRY;

  exit(EXIT_SUCCESS);
}



/** EXAMPLE2: MULTIPLE CATCHES */
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>


#define FOO_EXCEPTION (1)
#define BAR_EXCEPTION (2)
#define GOO_EXCEPTION (3)

#define TRY do{ jmp_buf env; switch(setjmp(env)) { case 0:
#define CATCH(exception) break; case exception:
#define END_TRY } }while(0)
#define THROW(exception) longjmp(env, exception)

int main(int argc, char *argv[]) {

  TRY {
    printf("In TRY statement\n");
    THROW(GOO_EXCEPTION);
    printf("not reachable\n");
  }
  CATCH(FOO_EXCEPTION) {
    printf("FOO exception caught\n");
  }
  CATCH(BAR_EXCEPTION) {
    printf("BAR exception caught\n");
  }
  CATCH(GOO_EXCEPTION) {
    printf("GOO exception caught\n");
  }
  END_TRY;

  exit(EXIT_SUCCESS);
}


/** FINALLY BLOCK */

#define FOO_EXCEPTION (1)
#define BAR_EXCEPTION (2)
#define GOO_EXCEPTION (3)

#define TRY do{ jmp_buf env; switch(setjmp(env)) { case 0: while(1) {
#define CATCH(exception) break; case exception:
#define FINALLY break; } default:
#define END_TRY } }while(0)
#define THROW(exception) longjmp(env, exception)

int main(int argc, char *argv[]) {

  TRY {
    printf("In TRY statement\n");
    THROW(GOO_EXCEPTION);
    printf("not reachable\n");
  }
  CATCH(FOO_EXCEPTION) {
    printf("FOO exception caught\n");
  }
  CATCH(BAR_EXCEPTION) {
    printf("BAR exception caught\n");
  }
  CATCH(GOO_EXCEPTION) {
    printf("GOO exception caught\n");
  }
  FINALLY {
    printf("Finally \n");
  }
  END_TRY;

  exit(EXIT_SUCCESS);
}


以上是关于c_cpp 使用setjmp / longjmp的C中的异常的主要内容,如果未能解决你的问题,请参考以下文章

linux setjmp与longjmp的使用

使用 longjmp/setjmp 进行 C 错误处理都有哪些“好”方法?

UNIX环境高级编程 第8章函数setjmp 和 longjmp使用方法

setjmp和longjmp简介

C setjmp和longjmp

c setjmp longjmp