C异常处理如何处理异常派生类?

如果我正在捕获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;
}

输出:
赶上1
赶上2

转载注明原文:C异常处理如何处理异常派生类? - 代码日志