为什么这个程序没有捕获异常?

时间:2015-04-19 19:30:52

标签: c++ exception inheritance

我尝试使用异常打印类型名称,但我的程序似乎甚至没有捕获异常,而是似乎调用默认终止函数。我错过了什么?

#include <cstdio>
#include <exception>
#include <typeinfo>

namespace Error
{
    template<typename T>
    class Blah : std::exception
    {
        virtual const char* what() const throw()
        {
            return typeid(T).name();
        }
    };
}

void blah() {
    throw Error::Blah<int*********>();
}

int main()
{
    try
    {
        blah();
    }
    catch (std::exception& e)
    {
        std::puts(e.what());
    }
}

1 个答案:

答案 0 :(得分:10)

问题在于:

template<typename T>
class Blah : std::exception
//          ^^^^^^^^^^^^^^^

您继承私有(默认情况下class继承为private且您不添加说明符),因此std::exception不是一个可访问的基地你必须公开继承。

相关问题