系统标准异常库
-
#incldue
-
out_of_range 等…
#include<iostream>#include<string>using namespace std;//系统提供标准异常#include<stdexcept>class Person{public:Person(string name, int age){this->m_Name = name;//年龄做检测if (age<0 || age>200){//抛出越界异常//throw out_of_range("年龄越界了");throw length_error("长度越界了");}}string m_Name;int m_Age;};void test01(){try{Person p("张三", 300);}catch (out_of_range &e){cout << e.what()<<endl;}catch (length_error &e){cout << e.what() << endl;}}int main(){test01();system("pause");return 0;}
编写自己的异常类
-
自己的异常类需要继承于系统提供的类 exception
-
重写 虚析构 what()
-
内部维护错误信息,字符串
-
构造时候传入 错误信息字符串,what返回这个字符串
#include<iostream>using namespace std;#include<string>using namespace std;//系统提供标准异常#include<stdexcept>class MyOutofRangeException :public exception{public:MyOutofRangeException(string errorInfo){this->m_ErrorInfo = errorInfo;}virtual ~MyOutofRangeException(){}virtual const char *what()const{//返回 错误信息//string 转 char * .c_str()return this->m_ErrorInfo.c_str();}string m_ErrorInfo;};class Person{public:Person(string name, int age){this->m_Name = name;//年龄做检测if (age<0 || age>200){throw MyOutofRangeException(string ("我自己的年龄越界异常"));}}string m_Name;int m_Age;};void test01(){try{Person p("张三", 300);}catch (MyOutofRangeException &e){cout << e.what() << endl;}}int main(){test01();system("pause");return 0;}