在C语言中遇到异常错误进行处理时有五个常用方法,下面我们一起来看看一些实例演示,便于您在面对异常时能更快的找到解决方法
实例一 :使用exit()终止程序运行
#include
#include
voidDivideError(void)
{
printf("divide 0 error!\n");
}
doubledivide(double x,double y)
{
if(y==0) exit(EXIT_FAILURE);//此时EXIT_FAILURE=1
//也可以使用atexit()函数来注册异常处理函数,但此时异常处理函//数必须形如voidfun(void);
else return x/y;
}
intmain()
{
double x,y,res;
printf("x=");
scanf("%lf",&x);
printf("y=");
scanf("%lf",&y);
atexit(DivideError);
res=divide(x,y);
printf("result=%lf\n",res);
return 0;
}
实例二:使用assert(expression)
#include
#include
intmain()
{
int a,b,res;
res=scanf("%d,%d",&a,&b);
//scnaf函数返回从stdin流中成功读入的数据个数
assert(res==2); //如果res!=2,则出现异常
return 0;
}
实例三:使用全局变量errno来获取异常情况的编号
#include
#include
intmain()
{
char filename[80];
errno=0;
scanf("%s",filename);
FILE* fp=fopen(filename,"r");
printf("%d\n",errno); //如果此时文件打不开,那么errno=2
return 0;
}
实例四:使用goto实现局部跳转
#include
#include
intmain()
{
double x,y,res;
int tag=0;
if(tag==1)
{
Error:
printf("divide0 error!\n");
exit(1);
}
printf("x=");
scanf("%lf",&x);
printf("y=");
scanf("%lf",&y);
if(y==0)
{
tag=1;
goto Error;
}
else
{
res=divide(x,y);
printf("result =%lf\n",res);
}
return 0;
}
实例五:使用setjmp和longjmp实现全局跳转
#include
#include
jmp_buf mark; //保存跳转点上下文环境的结构体
void DivideError()
{
longjmp(mark,1);
}
intmain()
{
double a,b,res;
printf("a=");
scanf("%lf",&a);
printf("b=");
scanf("%lf",&b);
if(setjmp(mark)==0)
{
if(b==0) DivideError();
else
{
res=a/b;
printf("the result is%lf\n",res);
}
}
else printf("Divide 0 error!\n");
return 0;
}
标签:
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至hey@evget.com
文章转载自:网站转载