#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;
}
}
c++ 异常捕获
最新推荐文章于 2023-01-13 00:39:09 发布