我用下面的類爲我的例外,它工作正常:
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_;
};
我知道這並不回答你的問題,但你可能想在開始使用異常之前閱讀[this](http://www.codeproject.com/KB/cpp/cppexceptionsproetcontra.aspx)。關於異常好壞的堆棧溢出問題也有很多問題(答案大多不好)。 – Shahbaz