赞
踩
作者:解琛
时间:2020 年 12 月 18 日
#include <stdio.h> #include <setjmp.h> jmp_buf jumper; int fdf(int a, int b) { if (b == 0) { longjmp(jumper, -3); // 跳到以 jumper 所在的 jmp point,进行处理,-3 相当于具体的 exception code; } return a / b; } int main() { int jstatus = setjmp(jumper); // 相当于 java catch,如果发生 jumper 异常,那么会跳回到这个 jmp point; if (jstatus == 0) { // 第一次执行的时候是正确的 setjmp return 0; int a = 1; int b = 0; printf("%d/%d", a, b); int result = fdf(a, b); printf("=%d\n", result); } else if (jstatus == -3) printf(" --> Error:divide by zero\n"); else printf("Unhandled Error Case"); return 0; }
执行结果如下。
xiechen@xiechen-Ubuntu:~/6.本地实验中心/3.c$ gcc 4.异常捕获.c
xiechen@xiechen-Ubuntu:~/6.本地实验中心/3.c$ ./a.out
1/0 --> Error:divide by zero
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。