复试C++ 异常 看程序写结果
就算每一个case后面都没有break , throw相当于起了break的作用?
#include <iostream>
#include <stdexcept>
using namespace std;
class ErrorA: public runtime_error{
public:
ErrorA():runtime_error{"errorAAAA"} {}
};
class ErrorB: public runtime_error{
public:
ErrorB():runtime_error{"errorBBBB"} {}
};
class ErrorC: public ErrorA{
public:
ErrorC(){
runtime_error{"errorCCCC"};
}
};
int main(){
for(int i = 0 ;i < 4; i++){
try{
switch(i){
case 0:throw runtime_error{"runtime_error1111"}; break;
case 1:throw ErrorA();
case 2:throw ErrorB();
case 3:throw ErrorC();
}
}catch(ErrorA &err){
cout << err.what() << endl;
}catch(ErrorB &err){
cout << err.what() << endl;
}catch(ErrorC &err){
cout << err.what() << endl;
}catch(runtime_error &err){
cout << err.what() << endl;
}
}
return 0;
}
结果
runtime_error1111
errorAAAA
errorBBBB
errorAAAA
为什么最后一个输出是errorAAAA?因为errorA是C的父类,能捕获父类的catch一定可以捕获子类的,所以errorC被第一个catch捕获了 所以建议多重catch语句把子类异常的写在前面 不然被捕获了的话之后的catch就不生效了