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\n",errno); if (errno != 0) { printf("程序出错...\n"); } }
此代码中errno=33,是一个宏定义。 #define EDOM 33 /* Math argument out of domain of func */
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\n",errno); perror("perror报错"); printf("strerror报错: %s\n", strerror(errno)); if (errno!=0) { printf("程序出错...\n"); } }
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\n", errno); perror("perror报错"); printf("strerror报错: %s\n", 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:\Users\AndyMi\Documents\C\Project3.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); } }
来源:https://www.cnblogs.com/tigerlion/p/11191708.html