try:执行的代码块
catch:捕获的异常
throw:主动排除异常
#include <iostream>
#include <string>
using namespace std;
int main()
{
try {
int a;
cin >> a;
if (a > 10) {
throw "input number is bigger than 10!";
} else {
throw a;
}
}
// 捕获异常打印的字符串
catch(const char* message){
cout << "input number is too big!" << endl;
}
// 捕获int类型
catch (const int a) {
cout << "input number is " << a << endl;
}
}
可以用类对象作为异常
派生类类型的异常会隐式转换为基类类型的异常,会被基类类型的catch捕获
注意:这里catch需要按引用捕获,不然只会捕获基类
异常的黄金规则:按值抛出异常,按引用捕获异常
只包含throw关键字可以重新抛出异常,在catch中捕获的异常会传给下一个try
catch(...):捕获所有异常
noexcept:在函数头中追加这个关键字,表示不会抛出异常。析构函数被隐式声明为noexcept
RAII:资源获取即初始化
标准库异常
std::exception