【问题标题】:Why does this program fail to catch an exception? [duplicate]为什么这个程序无法捕获异常? [复制]
【发布时间】:2015-06-26 09:44:12
【问题描述】:

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

#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());
    }
}

【问题讨论】:

    标签: c++ exception inheritance


    【解决方案1】:

    问题出在这里:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多