try检测异常
throw抛出
catch处理异常
C++处理异常
1 #include <iostream> 2 3 class wrong//表示错误类型 4 { 5 6 }; 7 8 int intdiv(int a, int b) 9 { 10 try 11 { 12 if (!b) 13 { 14 throw wrong(); 15 } 16 17 int c = a / b; 18 return a / b; 19 } 20 catch (wrong) 21 { 22 std::cout << "除法异常已经处理" << std::endl; 23 return -1; 24 } 25 } 26 27 void main() 28 { 29 int x, y; 30 std::cin >> x >> y; 31 32 std::cout << intdiv(x, y) << std::endl; 33 }
类中异常
1 #include <iostream> 2 3 class box 4 { 5 public: 6 box(int data) :a(data) 7 { 8 std::cout << "开始构造" << std::endl; 9 10 if (data < 100) 11 { 12 throw small(); 13 } 14 else if (data > 10000) 15 { 16 throw big(); 17 } 18 } 19 class big {}; 20 class small {}; 21 private: 22 int a; 23 }; 24 25 void main() 26 { 27 try 28 { 29 box newbox(200); 30 } 31 catch (box::big) 32 { 33 std::cout << "长度太长" << std::endl; 34 } 35 catch (box::small) 36 { 37 std::cout << "长度太短" << std::endl; 38 } 39 }
异常类的派生
适用于处理违反了2个规则的异常
1 #include <iostream> 2 #include <string> 3 4 class box//正方体 5 { 6 public: 7 box(int data) 8 { 9 std::cout << "开始构造" << std::endl; 10 11 if (data == 0) 12 { 13 zero z1(22); 14 z1.seterror(21); 15 16 throw z1; 17 } 18 else if (data > 0 && data<100) 19 { 20 throw small(); 21 } 22 else if (data>10000) 23 { 24 throw big(); 25 } 26 else if (data > 100 && data < 10000) 27 { 28 a = data; 29 } 30 else 31 { 32 throw wrong{}; 33 } 34 } 35 36 int gettiji() 37 { 38 return a*a*a; 39 } 40 41 class wrong {}; 42 class big {}; 43 class small {}; 44 45 class zero :public small//两种错误的处理方式都接受 46 { 47 public: 48 int errorcode; 49 zero(int i) :errorcode(i) 50 { 51 52 } 53 void seterror(int i) 54 { 55 errorcode = i; 56 } 57 }; 58 private: 59 int a;//变长 60 }; 61 62 void main() 63 { 64 65 try 66 { 67 box newbox(0); 68 } 69 70 catch (box::wrong) 71 { 72 std::cout << "正方体长度异常" << std::endl; 73 } 74 catch (box::big) 75 { 76 77 std::cout << "正方体长度太长" << std::endl; 78 } 79 catch (box::zero w) 80 { 81 if (w.errorcode == 22) 82 { 83 std::cout << "22号错误正方体长度不可以为0" << std::endl; 84 } 85 else 86 { 87 std::cout << "fei22号错误正方体长度不可以为0" << std::endl; 88 } 89 90 } 91 catch (box::small) 92 { 93 std::cout << "正方体长度taiduan" << std::endl; 94 } 95 }
MFC处理异常
1 void openfile() 2 { 3 TRY 4 { 5 CFile file(_T("F:\users\123.txt"), CFile::modeRead);//尝试动作,如果异常,抛出异常 6 } 7 CATCH(CFileException, e)//文件的异常 8 { 9 if (e->m_cause == CFileException::fileNotFound) 10 { 11 cout << "文件不存在,请认真检查"; 12 } 13 } 14 END_CATCH 15 }