2017-02-27 81 views
0

当您丢弃并未处理std::runtime_error时,终端自动打印what()的结果,使调试变得更容易。例如:如何在抛出未处理的自定义异常之后调用what()?

#include <iostream> 

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

控制台输出:

​​

这个类派生自定义异常类表现出同样的行为,从头开始做的异常类不这样做,默认情况下。

但我想创建的异常类不能从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;进入析构函数并没有帮助。

请帮我提一下您的建议!谢谢。

+4

“但我想创建的异常类不能从std :: runtime_error派生。” - 为什么不? –

+2

在主体中捕获你的异常,并做他们想要的。我不会依赖运行时为你做这件事。 –

+0

@NeilButterworth它迫使我使用某些数据类型或每次都将它们转换,它阻止了我创建一个我想用于我自己的项目的泛型异常类,我想知道如何添加此功能以便好奇心。我只是不喜欢这样。否则,我可以只使用std :: runtime_error本身...但我想通过自定义异常类,因为它可以确定的东西std :: runtime_error不能。 – Thynome

回答

4

最小例外界面使用what()std::terminate_handlerstd::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 ndler。

+0

你能解释一下如何正确地重写'std :: terminate_handler',以及如何将它集成到我的异常类中吗? – Thynome

+0

@Thynome我终于不确定一个'std :: terminate_handler'重写函数是否可以重新抛出并像'try {throw; } catch(const Custom_Exception&ce){/ * ... * /}'。 –

+0

你可以。 [except.handle]/7表示当由于throw *而输入std :: terminate()[...]时,隐式处理程序 被认为是活动的,因此您可以安全地从那里重新抛出异常。 –

0

你应该从获得的std ::例外,它提供了一个虚拟的析构函数和虚拟什么()方法的例外。如果你重写析构函数,你应该能够打印你的消息。

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

即使从不抛出异常,这是否会打印错误消息?而且即使它被抓住了? –

+0

哦,是的。每当异常被破坏时。所以πάνταῥεῖ与外部渔获的答案可能会奏效。 –

+0

输出错误信息不是析构函数的责任。这就是'what()'存在的原因,在需要时返回错误消息。 –

相关问题