gpt4 book ai didi

c++ - C++异常处理如何处理异常派生类?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:14:38 25 4
gpt4 key购买 nike

如果我正在捕获 BaseException,这是否也会捕获从 BaseException 派生的异常?异常处理是否关心继承等,还是只匹配捕获的确切异常类型?

class MyException {
...
};
class MySpecialException : public MyException {
...
};

void test()
{
try {
...
}
catch (MyException &e) {
//will this catch MySpecialException?
}
}

最佳答案

用代码很容易解释:http://ideone.com/5HLtZ

#include <iostream>

class ExceptionBase {
};

class MyException : public ExceptionBase {
};

int main()
{
try
{
throw MyException();
}
catch (MyException const& e) {
std::cout<<"catch 1"<<std::endl;
}
catch (ExceptionBase const& e) {
std::cout<<"should not catch 1"<<std::endl;
}

////////
try
{
throw MyException();
}
catch (ExceptionBase const& e) {
std::cout<<"catch 2"<<std::endl;
}
catch (...) {
std::cout<<"should not catch 2"<<std::endl;
}

return 0;
}

输出:
catch 1
catch 2

关于c++ - C++异常处理如何处理异常派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com