【问题标题】:overriding the what function in std::exception in c++在 c++ 中覆盖 std::exception 中的 what 函数
【发布时间】:2021-10-27 05:50:35
【问题描述】:

我正在尝试重写 what 函数以打印我自己的自定义错误消息。

所有消息都有相同的开头,因此我认为如果我可以执行以下操作会是最好的:

class Exception : public std::exception
{
    public:
    virtual const char* what() const throw() noexcept
    {
        return ("A game related error has occurred: " +  "class name");
        //note : "class name" above is the error message I want to print 
        //depending on the situation, which can vary a lot(we have 8 different messages)
    }
};


//examples of "class name" /otherwise known by us as error messages:

class IllegalArgument : public Exception {};

class IllegalCell  : public Exception {};

我的问题如下:

我不知道如何根据收到的错误打印不同的消息 没有在每个错误类中创建特殊的 what 函数 - 这意味着我必须向 IllegalArgument、IllegalCell 和所有其他错误类添加一个 what 函数,这在我看来很糟糕,因为它有太多的函数无法支持并不断更新超时。无论如何我可以避免这种情况,并且能够在主类中打印不同的消息 - 异常?

【问题讨论】:

  • 确保签名对于您使用的 C++ 版本是正确的:en.cppreference.com/w/cpp/error/exception/what(您现在有 throw() 和 noxcept,只需要一个)
  • 只需将类名传递给您的Exception 构造函数并在what() 中使用它。如果你对可能奇怪的类名感到满意,你可以使用typeid(*this).name() 来检索类名。
  • 我们使用的签名确实是正确的,我用的是c++11。
  • 霍尔特,你能再解释一下吗?
  • @Saleh 看看我的回答。

标签: c++ c++11 exception overriding virtual-functions


【解决方案1】:

您可以将类的名称传递给Exception构造函数并存储名称:

class Exception : public std::exception {
public:
    virtual const char *what() const noexcept {
        return m_.c_str();
    }

protected:
    Exception(std::string const& name) : m_{"A game related error has occurred: " + name} {}

private:
    std::string m_;
};

class IllegalArgument: public Exception {
public:
    IllegalArgument() : Exception("IllegalArgument") {}
};

如果您不想每次都编写默认构造函数,您可以编写一个宏来定义您的子异常。


如果您对生成的名称感到满意,另一种选择是使用typeid(),例如

class Exception : public std::exception {
public:
    virtual const char *what() const noexcept {
        // you need a static here to maintain the buffer since you are returning a
        // const char*, not a string, and you cannot construct this string in the
        // constructor because typeid() will not work properly in the constructor
        //
        static const std::string s = 
            std::string("A game related error has occurred: ") + typeid(*this).name();
        return s.c_str();
    }
};

class IllegalArgument : public Exception { };

typeid(*this).name() 生成的名称不是标准的,例如 wit gcc 我得到15IllegalArgument,所以这取决于你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多