在C/C++编程中,错误码是非常常用的一个基础组件,程序员往往自己定义枚举,或者使用语言里已有的一些值,例如EINVAL、ERANGE等等,这些值来源于POSIX,在标准库里也有一份:
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/errno.h.html
https://en.cppreference.com/w/cpp/error/errno_macros
举例:
#include <stdio.h>
#include <errno.h>
int fun(i) {
switch (i) {
case 1:
return -EFAULT;
case 2:
return -EFBIG;
default:
return 0;
}
}
int main() {
for (int i = 1; i <= 3; i++) {
int err = fun(i);
if (err) {
printf("%d\n", err);
}
}
return 0;
}
输出:
-14
-27
在C++11中引入了<system_error>库,将错误码封装成了一个类std::error_code,它可以通过一个枚举值std::errc来构造,并且可以用.message()成员方法取出来其字符串形式,增加可读性。(不过这个库很少用到。。)
举例:
#include <cstdio>
#include <system_error>
std::error_code fun(int i) {
switch (i) {
case 1:
return std::make_error_code(std::errc::bad_address);
case 2:
return std::make_error_code(std::errc::file_too_large);
default:
return std::error_code(); //没有错误,调用其默认构造函数
}
}
int main() {
for (int i = 1; i <= 3; i++) {
std::error_code err = fun(i);
if (err) {
printf("%s\n", err.message().c_str());
}
}
return 0;
}
输出:
Bad address
File too large