c++ - 扩展 std::exception 类:程序不会执行适当的 catch 处理程序

标签 c++ exception gcc exception-handling

我从 std::exception 派生了一个类:

class exc : public std::exception
{
public:
    exc(const text::_char *) throw();
    exc(const exc &) throw();
    virtual ~exc() throw();

    text::_char *m_what;
};

我有两个包装函数来抛出我的异常类型:

PS:dbg_out 指的是 std::cout。 text 是 std::basic_string<< char >> 的后代。

void throw_exception(const text::_char *p_format, ...)
{
    va_list l_list;

    text l_message;

    va_start(l_list, p_format);
    l_message.format_va(p_format, l_list);
    va_end(l_list);
    throw exc((const text::_char *)l_message);
}

void throw_exception_va(const text::_char *p_format, va_list p_list)
{
    text l;
    exc l_exc((const text::_char *)l.format_va(p_format, p_list));

    dbg_out << l_exc.m_what;
    throw l_exc;
}

主要功能:

int main(int, char **)
{
    try
    {
        throw_exception("hello world!");
        return 0;
    }
    catch(const std::exception &p)
    {
        return 0;
    }
}

我的程序崩溃并显示此消息:

hello world!
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

我使用 gcc 编译器(最新的 MinGW 版本)

我的程序没有进入main函数中的catch handler。它不调用类 exc 的复制构造函数。它看起来像 gcc 生成的代码,不将 exc 识别为 std::exception 的后代。

我做错了什么?

最佳答案

我敢打赌你的问题出在这条线上:

throw exc((const text::_char *)l_message);

你提到 text源自 basic_string<char> . basic_string<char> 没有支持的类型转换至 const char* .因此,除非您在派生类中提供自己的转换运算符,否则您会在这里陷入未定义/未指定的行为。尝试将上面的行更改为:

throw exc(l_message.c_str());

关于c++ - 扩展 std::exception 类:程序不会执行适当的 catch 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392237/

相关文章:

c - g_atomic_int_get 保证对另一个线程的可见性?

c - 将变量类型作为函数参数传递

c++ - 在 STL 优先级队列 C++ 中实现 decreaseKey

c++ - 为 iPhone 构建时出现 GCC 链接器错误

c++ - 在 C++ 中初始化一个静态成员(一个数组)

.net - .net 中不同类型的异常

generics - 如何在F#中声明通用异常类型

java - 尽管捕获了 IOException 还是编译器错误

c++ - 我尝试在 win32 应用程序中访问空指针的值,但没有发生访问冲突

c++ - 根据用户输入排序或合并排序