c语言没有try catch的替代方案

Judy ·
更新时间:2024-09-20
· 856 次阅读

setjmp与longjmp

后缀jmp指的就是jump,关看名字就能猜到这哥俩是干啥的了。使用他们俩就可以让程序控制流转移,进而实现对异常的处理。

异常处理的结构可以划分为以下三个阶段:

准备阶段:在内核栈保存通用寄存器内容 处理阶段:保存硬件出错码和异常类型号,然后向当前进程发送信号 恢复阶段:恢复保存在内核栈中的各个寄存器内容,返回当前进程的断电处继续执行

过程有点类似递归,只有文字你可能看的有点云里雾里,我们结合一个小例子来看看

#include <stdio.h> #include <setjmp.h> static jmp_buf buf; void second(void) { printf("second\n"); // 跳回setjmp的调用处 - 使得setjmp返回值为1 longjmp(buf, 1); } void first(void) { second(); //这行到不了,因为second里面longjmp已经跳转回去了 printf("first\n"); } int main() { int rc; rc = setjmp(buf); if (rc==0) { // 进入此行前,setjmp返回0 first(); } // longjmp跳转回,setjmp返回1,因此进入此行 else if(rc==1){ printf("main\n"); } return 0; } /* the ressult as: second main */

现在我们再来看看两个函数的声明:

setjmp(env) :将程序上下文存储在env中 longjmp(env,status):env指代setjmp中所保存的函数执行状态变量,status则是作为setjmp的返回值

当然你也可以用switch代替上面的if else,其实try catch就相当于上面的那个函数你可以参考这个实现try catch。

signal信号处理

个人觉得这个在linux下更好用,并且也提供了更多的信号量宏。

下面给出的是signal头文件中的定义

#define SIGINT 2 // interrupt #define SIGILL 4 // illegal instruction - invalid function image #define SIGFPE 8 // floating point exception #define SIGSEGV 11 // segment violation #define SIGTERM 15 // Software termination signal from kill #define SIGBREAK 21 // Ctrl-Break sequence #define SIGABRT 22 // abnormal termination triggered by abort call

这里仅给出维基上的例子

#include <signal.h> #include <stdio.h> #include <stdlib.h> static void catch_function(int signal) { puts("Interactive attention signal caught."); } int main(void) { if (signal(SIGINT, catch_function) == SIG_ERR) { fputs("An error occurred while setting a signal handler.\n", stderr); return EXIT_FAILURE; } puts("Raising the interactive attention signal."); if (raise(SIGINT) != 0) { fputs("Error raising the signal.\n", stderr); return EXIT_FAILURE; } puts("Exiting."); return 0; }

总结

到此这篇关于c语言没有try catch的替代方案的文章就介绍到这了,更多相关c语言try catch内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

您可能感兴趣的文章:C++编程异常处理中try和throw以及catch语句的用法C++中try throw catch异常处理的用法示例C++异常处理 try,catch,throw,finally的用法c++中try catch的用法小结C++之try catch 异常处理入门实例



try catch catch try C语言

需要 登录 后方可回复, 如果你还没有账号请 注册新账号