2011-11-16 51 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