这篇文章将为大家详细讲解有关如果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
*/
现在我们再来看看两个函数的声明:
当然你也可以用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怎么办?就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。