处理错误
C++用异常、返回bool或错误码、特殊返回值、对象内部状态码表示错误。
C++标准库一般用异常表示错误,如vector数组.at访问越界std::out_of_range异常,生成随机数randon_device::operator()失败,正则表达式regex语法错误,new,stoi失败则抛异常;new (std::nothrow) 失败、malloc分配内存失败返回nullptr;strtoi无法转换时返回0,超范围返回LONG_MAX /LONG_MIN,设置errno为ERANGE;POSIX函数失败常返回-1且设errno。
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {
vector<int> a{1, 2, 3};
cout<< a.at(3)<<"!"<<endl;
return 0;
}
异常
异常在程序正常状态下,无(检查状态的)额外开销,性能高,防止错误被忽略的优点,代价是出现错误后处理效率可能低。
Google C++规范不推荐使用异常,而是尽快返回错误。主要原因是使用异常的代价可能高于收益,需要额外代价妥当处理异常,处理有很大的难度,同时开源的库代码未用异常,Google工程师们通过其他方式处理错误事半功倍,以高效利用已开发的开源库。
We do not use C++ exceptions.
We don’t believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.
Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we’d like to use our open-source projects at Google and it’s difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch.
This prohibition also applies to exception handling related features such as std::exception_ptr and std::nested_exception.
本文探讨了C++中处理错误的不同方法,包括异常、返回bool或错误码,强调GoogleC++规范倾向于避免异常,提倡通过返回值或状态码来管理错误,以提高代码的可维护性和效率。

被折叠的 条评论
为什么被折叠?



