如何在抛出未处理的自定义异常后调用what()?

时间:2017-02-27 18:27:46

标签: c++ debugging exception custom-exceptions

当您抛出和未处理std::runtime_error时,终端会自动打印what()的结果,使调试变得更加容易。例如:

#include <iostream>

int main()
{
    throw std::runtime_error("This is an error message.\n");
}

控制台输出:

terminate called after throwing an instance of 'std::runtime_error'
what():  This is an error message.

此类派生的自定义异常类显示相同的行为,默认情况下从头开始的异常类不会这样做。

但我想要创建的异常类不能从std::runtime_error派生出来。出于调试目的,程序崩溃后仍应打印what() - 但我无法弄清楚如何无论如何都要这样做!有人能帮帮我吗?

此刻,它看起来像这样:

#include <iostream>

struct Custom_Exception
{
    std::string Msg;

    Custom_Exception(std::string Error_Msg) noexcept
    {
        Msg=Error_Msg;
    }

    std::string what() noexcept
    {
        return Msg;
    }
};

int main()
{
    throw Custom_Exception("This is an error message.\n");
}

控制台输出:

terminate called after throwing an instance of 'Custom_Exception'

错误消息中没有what(): ...将std::cout<<Msg;放入析构函数中也无济于事。

请帮助我提出建议!谢谢。

2 个答案:

答案 0 :(得分:4)

std::terminate_handler使用what()的最小异常界面为std::exception

struct Custom_Exception : public std::exception {
    std::string Msg;
public:
    Custom_Exception(std::string Error_Msg) noexcept : Msg(Error_Msg) {
    }

    const char* what() const { return Msg.c_str(); }
};

不继承std::exception界面的另一个选项是在main()

中捕获自定义例外
int main()
{
    try {
        throw Custom_Exception("This is an error message.\n");
    }
    catch(const Custom_Exception& ce) {
        std::cerr << ce.what() << std::endl;
    }
}

或覆盖并使用您自己的处理程序设置std::terminate_handler

答案 1 :(得分:0)

你应该从std :: exception派生你的异常,它提供了一个虚拟析构函数和虚拟的what()方法。如果覆盖析构函数,则应该能够打印消息。

#include <iostream>
#include <exception>

class Custom_Exception : std::exception
{
    char const* Msg;

    Custom_Exception(char const* Error_Msg) noexcept
    {
        Msg=Error_Msg;
    }

    Custom_Exception(Custom_Exception const& other)
    {
        Msg = other.Msg;
    }

    Custom_Exception& operator=(Custom_Exception const& other)
    {
        Msg = other.Msg;
        return *this;
    }

    virtual ~Custom_Exception()
    {
    }

    virtual char const* what() const noexcept
    {
        return Msg;
    }
};

int main()
{
    try 
    {
      throw Custom_Exception("This is an error message.\n");
    }
    catch (Custom_Exception& ex)
    {
      std::cout << "what(): " << ex.what();
    }
}