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++标准程序库》