【问题标题】:Inheriting Exceptions in C++11?在 C++11 中继承异常?
【发布时间】:2020-06-25 09:58:15
【问题描述】:

我有一个类叫Matrix<t>,教授让我写一个异常类:

Matrix::IllegalInitialization

这样就包含了what()这个函数,所以我写了(在Matrix.h中):

template<class T>
class Matrix<T>::IllegalInitialization {
public:
    std::string what() const {
        return "Mtm matrix error: Illegal initialization values";
    }
};

但是我有一个问题,这个类没有继承异常,如何解决这个问题?

我希望以下工作:

     try {
         Dimensions dim(0,5);
         Matrix<int> mat(dim);
} catch (const mtm::Matrix<int>::IllegalInitialization & e){ cout<< e.what() <<endl;
}

编辑: 我的代码应该是这样的吗?

template<class T>
class Matrix<T>::IllegalInitialization : public std::exception {
public:
   const char* what() const override {
      return "Mtm matrix error: Illegal initialization values";
   }
};

我得到:

错误:覆盖函数的异常规范比基础版本更宽松

【问题讨论】:

  • 只是继承自std::exception?我不明白这个问题
  • 请提供minimal reproducible example 和编译器错误(如果有),或说明实际和预期结果
  • 你知道如何从bar继承foo吗?
  • 您发布的代码中没有继承,但无论如何您可以从任意数量的类继承。有什么问题?
  • 请阅读minimal reproducible example。我们不需要看到Matrix&lt;T&gt; 并且您发布的代码不完整。尝试编译它会导致与您的问题无关的错误

标签: c++ exception


【解决方案1】:

std::exceptionwhat() 方法是(参见cppreference):

virtual const char* what() const noexcept;

您的方法未声明为noexcept,因此它不能覆盖std::exception::what()

【讨论】:

  • 我添加了 noexcept 并且一切正常,只是总结一下我的代码现在写得好吗?
  • @Daniel 您需要了解,当我只能看到代码的片段时,我无法告诉您代码是否正确。如前所述,您发布的代码不完整,当我尝试编译它时,我收到与您的问题无关的错误。无论如何,最终总是你必须了解每一个细节并确保代码是正确的
  • @Daniel 继承自 std::runtime_error 更方便,因为它已经实现了 what 和一个构造函数,该构造函数接受要打印的字符串
  • 但是 const 应该出现在最后还是我写的那样(const 表示 *this 不会受到影响)
【解决方案2】:

这是一个代码行数稍多的示例,但更灵活

使用示例:

try {
    throw MatrixErrors{ErrorCode::kIllegalInitialization};
} catch (const MatrixErrors& error) {
    std::cerr << error.what() << std::endl;
    return 1;
}

代码:

enum class ErrorCode {
  kIllegalInitialization,
};

// Helper function to get an explanatory string for error
inline std::string GetErrorString(ErrorCode error_code) {
  switch (error_code) {
    case ErrorCode::kIllegalInitialization:
      return "Mtm matrix error: Illegal initialization values";
  }
  return {};
}

class MatrixErrors : public std::runtime_error {
 public:
  explicit MatrixErrors(ErrorCode error_code) : std::runtime_error{GetErrorString(error_code)}, code_{error_code} {}

  ErrorCode GetCode() const noexcept { return code_; }

 private:
  ErrorCode code_;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2012-07-14
    • 2023-04-09
    • 2015-03-24
    • 2011-02-03
    相关资源
    最近更新 更多