2011-11-16 150 views
31

我剛剛創建了異常層次結構,並且想要將char*傳遞給我的派生類之一的構造函數,並顯示錯誤信息,但顯然std::exception沒有允許允許的構造函數我這樣做。然而,有一個叫做what()的班級成員表示可以傳遞一些信息。
我如何(可以嗎?)傳遞文本派生類std::exception,以傳遞信息與我的異常類,這樣我就可以在代碼的某個地方說:從std :: exception繼承的正確方法

throw My_Exception("Something bad happened."); 
+0

我知道這並不回答你的問題,但你可能想在開始使用異常之前閱讀[this](http://www.codeproject.com/KB/cpp/cppexceptionsproetcontra.aspx)。關於異常好壞的堆棧溢出問題也有很多問題(答案大多不好)。 – Shahbaz

回答

38

如果你想使用的字符串構造函數,你應該繼承std::runtime_errorstd::logic_error,它實現了一個字符串構造函數並實現了std :: exception :: what方法。

然後,它只是從您的新繼承類中調用runtime_error/logic_error構造函數,或者如果您使用的是C++ 11,則可以使用構造函數繼承。

4

what方法是虛擬的,其含義是您應該重寫它以返回您想要返回的任何消息。

+24

你的意思是重寫? – smallB

+0

沒有過載... – Hydro

5

如何:

class My_Exception : public std::exception 
{ 
public: 
virtual char const * what() const { return "Something bad happend."; } 
}; 

或者,創建一個構造函數接受的描述,如果你喜歡...

+1

@ user472155 +1爲好的答案。順便說一下,我認爲值得在這裏提一下,你在你的例子中爲什麼函數提供的簽名,只暗示C++ 11之前的代碼。 –

44

我用下面的類爲我的例外,它工作正常:

class Exception: public std::exception 
{ 
public: 
    /** Constructor (C strings). 
    * @param message C-style string error message. 
    *     The string contents are copied upon construction. 
    *     Hence, responsibility for deleting the char* lies 
    *     with the caller. 
    */ 
    explicit Exception(const char* message): 
     msg_(message) 
     { 
     } 

    /** Constructor (C++ STL strings). 
    * @param message The error message. 
    */ 
    explicit Exception(const std::string& message): 
     msg_(message) 
     {} 

    /** Destructor. 
    * Virtual to allow for subclassing. 
    */ 
    virtual ~Exception() throw(){} 

    /** Returns a pointer to the (constant) error description. 
    * @return A pointer to a const char*. The underlying memory 
    *   is in posession of the Exception object. Callers must 
    *   not attempt to free the memory. 
    */ 
    virtual const char* what() const throw(){ 
     return msg_.c_str(); 
    } 

protected: 
    /** Error message. 
    */ 
    std::string msg_; 
}; 
+0

「msg_」關鍵字來自哪裏?我不知道你可以在方法聲明的「:」之後調用聲明。我認爲這隻適用於基礎班。 – Nap

+1

msg_是異常的**保護**成員;它是std :: string的一個實例,因此它可以訪問它的.c_str成員函數(轉換爲c字符串)。 – MattMatt

+1

複製構造函數呢? – isnullxbh