c++ 差错和异常的处理(一)

//通过差错码可以对异常很好的处理

#include<iostream>
#include<system_error>
#include<future>
#include<exception>
#include<string>
template<typename T>
void processCodeException(const T& e)
{
    using namespace std;
    auto c = e.code();
    cerr << "-category:     " << c.category().name() << endl;
    cerr << "-value:        " << c.value() << endl;
    cerr << "-msg:          " << c.message() << endl;
    cerr << "-def category: " << c.default_error_condition().category().name() << endl;
    cerr << "-def value:    " << c.default_error_condition().value() << endl;
    cerr << "-def name      " << c.default_error_condition().message() << endl;
}
void processException()
{
    using namespace std;
    try
    {
        throw;
    }
    catch (const ios_base::failure& e)
    {
        cerr << "I/O EXCEPTION:  " << e.what() << endl;
        processCodeException(e);
    }
    catch (const system_error& e)
    {
        cerr << "SYSTEM EXCEPTION:  " << e.what() << endl;
        processCodeException(e);
    }
    catch (const future_error& e)
    {
        cerr << "FUTURE EXCEPTION:  " << e.what() << endl;
        processCodeException(e);
    }
    catch (const bad_alloc& e)
    {
        cerr << "BAD_ALLOC EXCEPTION:  " << e.what() << endl;
        //processCodeException(e);
    }
    catch (const exception& e)
    {
        cerr << "EXCEPTION:  " << e.what() << endl;
    }
    catch (...)
    {
        cerr << "EXCEPTION(unknown)" << endl;
    }
}
int main()
{
    try
    {
        //手动抛出异常
        //error_code(int _Val, const error_category& _Cat) _NOEXCEPT
        //error_code的一个构造函数_Val是枚举值表示错误的种类
        //因为error_category是抽象类不能构造对象,因此通过函数返回
        std::system_error e(std::error_code(5,std::system_category()));
        throw e;
    }
    catch (...)
    {
        processException();
    }
    system("pause");
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值