c++ 错误码

std::error_code

std::error_code 是依赖平台的错误码。每个 std::error_code 对象,保有一个源于操作系统或某些低层接口的错
误码,和一个指向 std::error_category 类型对象的指针。错误码的值在错误类别之间可以不唯一

class error_code
{
public:
    /**
    默认为错误码0,系统错误类别 _Myval(0),_Mycat(&system_category())
    */
    error_code() noexcept;
    error_code(int _Val, const error_category& _Cat) noexcept;
    //提供错误枚举值到错误码的转换,stl支持std::errc,std::io_errc,std::future_errc枚举类的转换
    template<class _Enum,enable_if_t<is_error_code_enum_v<_Enum>, int> = 0>
    error_code(_Enum _Errcode) noexcept;
    void assign(int _Val, const error_category& _Cat) noexcept;
    /**
    设值为无错状态_Myval = 0;_Mycat = &system_category();
    */
    void clear() noexcept;
    /**
    获取错误值
    */
    int value() const noexcept;
    /**
    获取类别
    */
    const error_category& category() const noexcept;
    /**
    向平台无关的error_condition提供转换(category().default_error_condition(value()));
    */
    error_condition default_error_condition() const noexcept;
    /**
    获取错误信息(category().message(value()));
    */
    string message() const;
    /**
    判断是否有错
    */
    explicit operator bool() const noexcept;

private:
    int _Myval;	//stored error number
    const error_category *_Mycat;// pointer to error category
};

其他

  1. is_error_code_enum//实现采用SFINAE(Substitution Failure Is Not An Error)SFINAE
  2. make_error_code

示例

#include <iostream>
#include <system_error>
#include <thread>
using namespace std;

int main()
{
    std::error_code ec(1, system_category());
    cout << ec.message().c_str() << endl
         << ec.value() << endl
         << ec.category().name() << endl;

    cout << "--------" << endl;
    //std::system_error 异常 内部就是通过error_code实现的

    try
    {
        thread().join();
    }
    catch (const std::system_error& e)
    {
        cout << e.code().message().c_str() << endl
            << e.code().value() << endl
            << e.code().category().name() << endl;
    }
    catch (...)
    {
        cout << "other error" << endl;
    }
    return 0;
}

示例结果

函数不正确。

1
system
--------
invalid argument
22
generic
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值