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

setjmp与longjmp

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

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

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

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

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

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

当然你也可以用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内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

—-想了解c语言没有try catch的替代方案分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/485053.html

(0)
上一篇 2020年11月10日
下一篇 2020年11月10日

精彩推荐