#include <iostream>
using namespace std;
class A_except :public std::exception
{
public:
char const* what()const {return "A_except(what())";}
void printf()const { std::cout << "A_except(printf())\n"; }
};
void f(int a)
{
if (!a) throw A_except();//自定义类型异常
if (a < 0) throw a; // int类型异常
std::cout << a << std::endl;
}
int main()
{
try
{
f(1);
f(0); // 出现异常,try中该行代码后续代码不执行,调到对应的catch中
f(-1);
}
catch (int a)
{
std::cout << "int error"<< a << std::endl;
}
catch (const std::exception& e)// 正常调用A_except::what(),what为虚函数
{
std::cout << e.what() << std::endl;
}
catch (const A_except &e)// 被catch (const std::exception& e)屏蔽(编译成功,不一定放在基类前面,但是会被屏蔽)
{
std::cout << e.what() << std::endl;
e.printf();
}
catch (...)
{
std::cout << "error" << std::endl;
}
return 0;
}