创建自己的异常(2种方法)C

Creating own exceptions (2 ways) c++

本文关键字:方法 2种 自己的 异常 创建      更新时间:2023-10-16

我被要求通过从标准库std :: logic_error异常来创建自定义。首先,我试图通过这本书做事:

class CustomException: public std::logic_error
{
  virtual const char* what() const throw()
  {
    return "Exception raised";
  }
};

但后来我的同事也得到了这项任务,向我展示了另一种处理此问题的方法:

class CustomException:public std::logic_error {
 using std::logic_error::logic_error;
public:
    const static std::string ExceptionText;
};

除了需要以不同的方式传递的信息之外,这两个事实的主要区别是什么?具体来说,我不知道使用语句在第二个选项中做什么。

它们并不完全相同。

在您的同事版本中:

    // This does nothing.
    // Delete it and the rest of the class is unchanged.
    const static std::string ExceptionText;

class CustomException:public std::logic_error {
    // This line basically inherits the base class constructor(s)
    // Which allows you to construct your exception like others.
    using std::logic_error::logic_error;
};

您可以将上述视为:

class CustomException: public std::logic_error {
    public:
        CustomException(std::string const& emsg)
            : logic_error(emsg)
        {}
        CustomException(char const* emsg)
            : logic_error(emsg)
        {}
        // And a couple of more
};

注意:基类上的what()功能将返回对您在开始时传递的消息的引用。

另一种选择(如果要保留原始消息)。

class CustomException: public std::logic_error
{
    public:
        CustomException()
            : logic_error("Exception raised")
        {}
        // The default "what()" will return the above message.
};
相关文章: