扩展std :: exception类:程序将不会执行相应的catch处理程序 [英] Extending the std::exception class : program won't execute the appropriate catch handler

查看:124
本文介绍了扩展std :: exception类:程序将不会执行相应的catch处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have derived a class from std::exception:

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

    text::_char *m_what;
};

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

I have two wrapper functions to throw my exception type:

PS:dbg_out指的是std :: cout。文本是std :: basic_string的一个后代<<< char >>。

PS: dbg_out refers to std::cout. text is a descendant of 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;
    }
}

我的程序与此消息崩溃:

My program crashes with this message:

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版本)

I use gcc compiler (latest MinGW version)

我的程序没有在主函数中输入catch处理程序。它不调用类exc的复制构造函数。看起来像由gcc生成的代码,不能识别为std :: exception的后代。

My program does not enter the catch handler in the main function. It doesn't call the copy constructor of class exc. It looks like the code generated by gcc, does not recognize exc as a descendant of std::exception.

我做错了什么?

推荐答案

你的问题在这一行:

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

您提到文本派生自的basic_string<炭> 。没有从 basic_string< char> const char * 的支持转换。因此,除非您在派生类中提供自己的转换运算符,否则在这里可能会出现未定义/未指定的行为。尝试更改以上行:

You mention text is derived from basic_string<char>. There is no supported cast from basic_string<char> to const char*. So unless you're providing your own conversion operator in the derived class, you're kind of off into undefined/unspecified behavior here. Try changing the above line to:

throw exc(l_message.c_str());

这篇关于扩展std :: exception类:程序将不会执行相应的catch处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆