为什么此程序无法捕获异常

Why does this program fail to catch an exception?

本文关键字:捕获异常 程序 为什么      更新时间:2023-10-16

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

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

问题就在这里:

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

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