标准异常库
- #incldue <stdexcept>
- throw out_of_range(”aaa”) 。。。
- catch(out_of_range & e) cout << e.what();
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <stdexcept> //标准异常库 using namespace std; //exception class Person { public: Person(string name, int age) { this->m_Name = name; if (age < 0 || age>200) { throw out_of_range("年龄越界了!"); } else { this->m_Age = age; } } string m_Name; int m_Age; }; void test01() { try { Person p1("张三", 300); } catch (exception& e) //使用系统提供的标准异常 多态 { cout << e.what() << endl; } } int main() { test01(); system("Pause"); return 0; }
结果: