zoukankan      html  css  js  c++  java
  • C语言讲义——错误处理

    errno

    • C语言不提供对错误处理的直接支持。
    • 以返回值的形式表示是否出错。

    • 在发生错误时,大多数的C函数调用返回1或NULL。
    • 同时设置一个错误代码errno(全局变量),表示在函数调用期间发生了错误。
    #include <errno.h> 或 #include <stdlib.h>
    
    • 可以通过检查返回值,然后根据返回值决定怎么处理
    • 把errno设置为0(没有错误),是一种良好的编程习惯
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    main() {
    	errno = 0;
    	// 平方根
    	int y = sqrt(-1);
    	printf("errno = %d
    ",errno);
    
    	if (errno != 0) {
    		printf("程序出错...
    ");
    	}
    }
    
    此代码中errno=33,是一个宏定义。
    #define EDOM 33 /* Math argument out of domain of func */
    
    

    更多errno点击这里查看

    perror()和strerror()

    • perror()显示错误信息
      来自:stdio.h
    • strerror(errno)将错误信息返回一个指针,指向描述错误信息的字符串
      来自:string.h
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <math.h>
    main() {
    	errno = 0;
    	// 平方根
    	int y = sqrt(-1);
    	printf("errno = %d
    ",errno);
    
    	perror("perror报错");
    	printf("strerror报错: %s
    ", strerror(errno));
    	if (errno!=0) {
    		printf("程序出错...
    ");
    	}
    }
    
    errno = 33
    perror报错: Domain error
    strerror报错: Domain error
    程序出错...
    

    应用举例

    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    extern int errno ;
    main () {
    	FILE * pf;
    	errno = 0;
    	pf = fopen ("unexist.txt", "rb");
    	if (pf == NULL) {
    		printf("错误号: %d
    ", errno);
    		perror("perror报错");
    		printf("strerror报错: %s
    ", strerror(errno));
    	} else {
    		fclose (pf);
    	}
    }
    

    *诊断·断言

    #include <stdio.h>
    #include <assert.h>
    main() {
    	int n1 = 1;
    	int n2 = 0;
    	// 不满足条件,中断
    	assert(n2!=0);
    	int n3 = n1/n2;
    	printf("---%d---",n3);
    }
    
    Assertion failed!
    
    Program: C:UsersAndyMiDocumentsCProject3.exe
    File: main.c, Line 10
    
    Expression: n2!=0
    
    This application has requested the Runtime to terminate it in an unusual way.
    Please contact the application's support team for more information.
    

    *使用信号处理错误

    include <signal.h>提供了处理异常情况的工具,称为“信号”。

    • signal()函数安装一个信号处理函数。

    • raise()触发信号。

    #include <stdio.h>
    #include <signal.h>
    
    void printErr(int sig) {
    	printf("出现错误%d", sig);
    }
    main () {
    	//说明:
    	//被安装的函数需要一个参数
    	//这个参数是信号编码
    	//这里使用SIGINT宏,表示终止进程或中断进程,对应为2
    	signal(SIGINT, printErr);
    	int n1 = 10;
    	int n2 = 0;
    	if (n2 == 0) {
    		raise(SIGINT);
    	} else {
    		printf("除法结果为:%d", n1/n2);
    	}
    }
    
  • 相关阅读:
    tomcat7的catalina.sh配置说明
    nginx防攻击的简单配置
    linux系统自签发免费ssl证书,为nginx生成自签名ssl证书
    mysql ERROR 1045 (28000): Access denied for user 'root'@'localhost'
    /var/log/secure 文件清空
    Linux日志文件
    记一次网站被挂马处理
    Uedit32对文本进行回车换行
    安装mysql血泪史。
    mysql-8.0.19安装教程(Windows)
  • 原文地址:https://www.cnblogs.com/tigerlion/p/11191708.html
Copyright © 2011-2022 走看看