C++里try,catch,throw的用法
1 // 12333.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include "opencv2/opencv.hpp" 6 #include "string" 7 #include "iostream" 8 class Error 9 { 10 public: 11 virtual void show()=0;//纯虚函数 12 }; 13 14 class ageError:public Error 15 { 16 public: 17 void show() 18 { 19 std::cout<<"age is error"<<std::endl; 20 } 21 }; 22 23 class nameError:public Error 24 { 25 public: 26 void show() 27 { 28 std::cout<<"name is error"<<std::endl; 29 } 30 }; 31 class Person 32 { 33 public: 34 void setname(std::string name) 35 { 36 nameError na; 37 if(name=="exit") 38 throw na; 39 Person::name=name; 40 } 41 void setyear(int age) 42 { 43 ageError ag; 44 if(age<0||age>100) 45 throw ag; 46 Person::age=age; 47 } 48 protected: 49 private: 50 int age; 51 std::string name; 52 }; 53 int main() 54 { 55 try 56 { 57 Person a; 58 a.setname("exit"); 59 a.setyear(-1); 60 } 61 catch (Error& er) 62 { 63 er.show(); 64 } 65 getchar(); 66 return 0; 67 }
1、各部分的功能:
try:试着运行代码
throw:抛出错误
catch:捕获错误,就是有错误就运行的代码
2、上面的代码运行到
"name is error"就停止运行了,而没有继续进行下去
3、Error有纯虚函数,是抽象类,不能直接定义对象,即Error er会报错,写成别名,却没有问题。