标准程序库异常

标准异常类的成员:
在上述继承体系中,每个类都有提供了构造函数、复制构造函数、和赋值操作符重载。
logic_error类及其子类、runtime_error类及其子类,它们的构造函数是接受一个string类型的形式参数,用于异常信息的描述;
所有的异常类都有一个what()方法,返回const char* 类型(C风格字
符串)的值,描述异常信息。



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<stdexcept>
using namespace std;
double mydiv(int x, int y) { if (y == 0) { throw out_of_range("除数不能为0"); }
return x / y; }
int main(char *argv[], int argc) { try { mydiv(100,0); } catch (out_of_range& oor) { cout << oor.what() << endl; } return 0; }
|
继承标准程序异常基类
继承异常基类需要重写virtual char const* what() const成员函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<exception>
using namespace std;
class MyException :public exception { public: MyException(const char * error) { pError = new char[strlen(error) + 1]; strcpy(pError,error);
} virtual char const* what() const { return pError; }
~MyException() { if (pError != NULL) { delete[] pError; pError = NULL;
} } private: char *pError; };
double div(double x,double y) { if (y == 0.0) { throw MyException("除数不能为0"); } return x / y; } int main(char *argv[], int argc) { try { div(100.0,0.0); } catch (exception& oor) { cout << oor.what() << endl; }
return 0; }
|