温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如果c语言没有try catch怎么办?

发布时间:2020-06-23 11:32:50 来源:亿速云 阅读:576 作者:清晨 栏目:编程语言

这篇文章将为大家详细讲解有关如果c语言没有try catch怎么办?,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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
*/

如果c语言没有try catch怎么办?

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

  • 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怎么办?就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI