【编程】C++语言编程规范-3

处理错误

C++用异常、返回bool或错误码、特殊返回值、对象内部状态码表示错误。
C++标准库一般用异常表示错误,如vector数组.at访问越界std::out_of_range异常,生成随机数randon_device::operator()失败,正则表达式regex语法错误,newstoi失败则抛异常;new (std::nothrow) 失败、malloc分配内存失败返回nullptrstrtoi无法转换时返回0,超范围返回LONG_MAX /LONG_MIN,设置errnoERANGE;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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值