(1)直接派生自exception,自己实现what()函数。

namespace MyLib {
  /* user-defined exception class
  * derived from a standard class for exceptions
  */
  class MyProblem : public std::exception {
    public:
    …
    MyProblem(…) { // special constructor }
    virtual const char* what() const throw() { // what() function
      …
    }
  };
  …
  void f() {
    …
    // create an exception object and throw it
    throw MyProblem(…);
    …
  }
}

(2)以那些派生自exception的特定异常类别作为基类,不需自己实现what()。

namespace MyLib {
  /* user-defined exception class
  * derived from a standard class for exceptions
  * that has a constructor for the what() argument
  */
  class MyRangeProblem : public std::out_of_range {
    public:
    MyRangeProblem (const string& whatString)
      : out_of_range(whatString) {
    }
  };
  …
  void f() {
    …
    // create an exception object by using a string constructor and throw it
    throw MyRangeProblem(“here is my special range problem”);
    …
  }
}

【学习资料】 《c++标准程序库》

相关文章:

  • 2021-07-04
  • 2022-01-29
  • 2021-11-16
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2022-12-23
猜你喜欢
  • 2021-10-29
  • 2021-07-06
  • 2021-12-11
  • 2022-02-01
  • 2022-12-23
  • 2021-12-03
相关资源
相似解决方案