复试C++ 异常 看程序写结果

uacs2024 / 2024-03-08 / 原文

就算每一个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