c++ - 从 std::exception 继承的正确方法

标签 c++ exception

我刚刚创建了异常层次结构并想将 char* 传递给我的一个派生类的构造函数,并带有一条消息告诉我出了什么问题,但显然 std::exception 没有允许我这样做的构造函数。然而,有一个名为 what() 的类成员表明可以传递一些信息。
我如何(我可以?)将文本传递给 std::exception 的派生类,以便通过我的异常类传递信息,所以我可以在代码中的某处说:

throw My_Exception("Something bad happened.");

最佳答案

我将以下类用于我的异常,它工作正常:

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() noexcept {}

    /** 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 noexcept {
       return msg_.c_str();
    }

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

关于c++ - 从 std::exception 继承的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8152720/

相关文章:

java - 如何从正在使用的文件中读取

c# - 如何捕获 DbUpdateException 唯一异常?

python - Python中如何处理异常?

java - NullPointerException 未引用任何对象

c++ - 在Windows中编译OpenSSL-生成的LIB为DLL文件使用了错误的名称

c++ - 使用Kinect时如何解决PCL中的OpenNi依赖错误?

c++ - OpenCV:我是否正确声明了矩阵?

c++ - 如果在头文件中定义函数,inline 关键字是否有意义?

C# 网络服务 : Throw exception with extra properties in JSON

.net - .net 中不同类型的异常