c++ 从标准异常类别(Exception Classes)派生新类别

(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++标准程序库》
原文链接: https://www.cnblogs.com/zhuyf87/archive/2012/12/30/2839727.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74040

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午4:13
下一篇 2023年2月9日 下午4:14

相关推荐