Inheriting Exceptions in C++11?

人盡茶涼 提交于 2021-01-29 05:17:46

问题


I have a class called Matrix<t>, My professor asked me to write an exception class:

Matrix::IllegalInitialization

Such that it includes the function what(), So I wrote (In Matrix.h):

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

But I have a problem that this class doesn't inherit Exceptions, how to fix this?

I want the following to work:

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

Edit: Is this how should my code look like?

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

I am getting:

error: exception specification of overriding function is more lax than base version


回答1:


The what() method of std::exception is (cf cppreference):

virtual const char* what() const noexcept;

Your method is not declared noexcept hence it cannot override std::exception::what().




回答2:


This is an example with a little bigger amount of code lines, but it more flexible

Usage example:

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

The code:

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_;
};


来源:https://stackoverflow.com/questions/62572708/inheriting-exceptions-in-c11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!