2011-07-22 26 views
1

如果我只是想抛出一个字符串,是不是有一个内置的类型,这样的地方我可以做C++基本字符串例外

throw standard_exception("This is wrong!"); 

还是我必须确定这样的标准异常导出从例外我自己?我知道这样做很简单,我只是认为这会很常见,而且会在某个地方定义。

由于

回答

6

std::runtime_errorstd::logic_error(均来自std::exception衍生)都具有采取串和重写what()构件函数返回提供的字符串构造函数。

+0

有趣的是,我发现每个链接都告诉一个不要抛出字符串,而是要定义自己的自定义异常。抛出runtime_error之类的选项永远不会被提及。 – Cookie

+0

我更喜欢为每个组件定义从'runtime_error'派生的异常;这样做会使得更正异常处理更容易一些,因为您可以处理特定错误并让其他错误在其他地方处理。不过,我确实直接使用'logic_error',但仅限于那些确实是逻辑错误的错误(例如代码错误),有点像断言。 –

+0

的确如此,但是如果所有人都希望线程在不影响应用程序的其余部分的情况下倒下,那么任何被异常捕获的东西都可以工作。我毫不怀疑,更先进的投掷和捕捉保证你自己的例外,但一个快速的“这是不可能的,现在死了”我认为这当然更合适。我觉得在我的情况下,按照这里的其他帖子中的建议定义自己的异常,或者C++常见问题解答过于矫枉过正,对于新手而言,并不是对异常最轻量级的介绍。 – Cookie

6

如果你想抛出一个字符串,可以仅通过写

throw "I'm throwing a string!"; 

这是不是一个特别好的主意,不过,因为它没有考虑好形式扔东西像char* S作为这样做例外。如果你想将字符串包装成某种形式的异常,你总是可以只使用runtime_errorlogic_error

throw logic_error("This is wrong!"); 
throw runtime_error("This is wrong!"); 
1

什么你可以抛出std::runtime_error或创建自己的类,从std::exception继承如下

#include <exception> 
#include <string> 


class myexcept : public std::exception 
{ 
private: 
    /** 
    * Reason for the exception being thrown 
    */ 
    std::string what_; 

public: 
    /** 
    * Class constructor 
    * 
    * @param[in] what 
    * Reason for the exception being thrown 
    */ 
    myexcept(const std::string& what) : what_(what){}; 


    /** 
    * Get the reason for the exception being thrown 
    * 
    * @return Pointer to a string containing the reason for the exception being thrown 
    */ 
    virtual const char* what() const throw() { return what_.c_str(); } 


    /** 
    * Destructor 
    */ 
    virtual ~myexcept() throw() {} 
}; 

throw myexcept("The reason goes here"); 
+1

[析构函数必须有一个异常规范。]( http://stackoverflow.com/questions/3233078/how-does-an-exception-specification-affect-virtual-destructor-overriding) –