c语言捕捉异常
2015-08-13 18:28
363 查看
闲暇之日阅读lua源码,发现原来C语言除goto之外的另一个处理异常的方法。既为setjump longjump两个函数,setjump相当于try,longjump相当于catch。与goto不同的是,longjump是全局的,比goto的作用范围更广。下面贴出简单用法:
#include <stdlib.h>
#include <setjmp.h>
jmp_buf jumper;
int fdf(int a, int b) {
if (b == 0)
{ // can't divide by 0
longjmp(jumper, -3);//跳到以jumper 所在的jmp point,进行处理,-3 相当于具体的exception code.
}
return a / b;
}
int main (int argc, char **argv)
{
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");
}
#include <stdlib.h>
#include <setjmp.h>
jmp_buf jumper;
int fdf(int a, int b) {
if (b == 0)
{ // can't divide by 0
longjmp(jumper, -3);//跳到以jumper 所在的jmp point,进行处理,-3 相当于具体的exception code.
}
return a / b;
}
int main (int argc, char **argv)
{
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");
}
相关文章推荐
- 二叉树的C++实现
- VS中的路径宏 vc++中OutDir、ProjectDir、SolutionDir各种路径
- 【c++】字符串中找出最长的连续数字字符串
- c语言为什么要声明
- Minimum Transport Cost
- 黑马程序员———C语言———【函数指针、指针函数、野指针、内存管理、const关键字】
- C++ primer 【笔记】关联容器 set
- C/C++:内存字节对齐详解
- VS2010 C++ 学习笔记(二) 内存管理 new delete
- 【一】C++基于C的一些改变
- 位运算
- C++ 共享数据(一)静态
- C++程序中调用WebService的实现
- [LeetCode] Best Time to Buy and Sell Stock II
- c++ 宏的使用
- OpenWRT开发之——对C++的支持(解决库依赖问题)
- 黑马程序员—-C语言入门十重奏之四相恋
- c++ 预处理的应用
- [LeetCode] Best Time to Buy and Sell Stock
- 链式队列的C++实现