c++ 异常捕获


#include <iostream>
#include<string>
#include<exception>
using namespace std;


class B
{
    B();
    virtual void method()const noexcept =0;


    // if the base class method with "noexcept",the derived class's method need set "noexcept"
    // however, if the base method can throw exceptions,the derived class can set both "noexcept" or nothing;

};

class A:public B
{
    A();
    void method()const noexcept override;

};

class C :public A
{
    C();
    void method()const noexcept final;

};

void method1(int a) noexcept
{
    cout << a;

    throw exception("s");//even it is not allow ,the compiler will not warn this error
}

// this is a old style for using NO exception throw
void method2(int a) throw()
{
    cout << a;
}


void method3(int a) noexcept(true)//no throw 
{
    cout << a;
}

void method4(int a) noexcept(false) // no control for throw
{
    cout << a;
}

void methodt5(int a) noexcept(noexcept(method4)) // method5 and method4 have the same settings
{
    cout << a;
}



int main()
{



    // pf1 set as method2,and not to throw
    void (*pf1)(int) noexcept = method3;


    //pf2 set individually. not as method3
    void (*pf2)(int) = method3;



    if (noexcept(method1))
    {
        cout << "method1" << " will not throw any exceptions" << endl;
    }



    double a = 2;
    double b = 0;


    try
    {

        double d = a / b; // allowed in c++ ,the return value is infinite

        cout <<endl<< d << endl;

        if (b == 0)
            throw exception("devide by zero exception");
    }

    catch (std::invalid_argument& ar)
    {
        cout << ar.what();
    }
    catch (exception& e)
    {
        cout << e.what() << endl;
    
    }
     
 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值