自定义异常类
C++自定义异常类,在抛出异常后必须去在可能发生异常的地方接收异常,如果只是抛出而不接收会报错
1 //Exception.h 2 3 #ifndef EXCEPTION_H 4 #define EXCEPTION_H 5 #include <string> 6 #include<sstream> 7 using namespace std; 8 class FirstException 9 { 10 public: 11 FirstException() {}; 12 FirstException(string str) 13 { 14 mes = str; 15 } 16 void outputMessage() 17 { 18 cout << mes; 19 } 20 private: 21 string mes; 22 }; 23 class SecondException 24 { 25 public: 26 SecondException() {}; 27 SecondException(string str) 28 { 29 mes = str; 30 } 31 void outputMessage() 32 { 33 cout << mes; 34 } 35 private: 36 string mes; 37 }; 38 class ThirdException 39 { 40 public: 41 ThirdException() {}; 42 ThirdException(string str) 43 { 44 mes = str; 45 } 46 void outputMessage() 47 { 48 cout << mes; 49 } 50 private: 51 string mes; 52 }; 53 54 double addanddiv(double a, double b, double c) 55 { 56 if (a < 0) 57 { 58 ostringstream s; 59 s << "a的值为" << a << " a应该大于0"; 60 throw FirstException(s.str()); 61 } 62 63 if (b < 0) 64 { 65 ostringstream s; 66 s << "b的值为" << b << " b应该大于0"; 67 throw SecondException(s.str()); 68 } 69 70 if (c < 0) 71 { 72 ostringstream s; 73 s << "c的值为" << c << " c应该大于0"; 74 throw ThirdException(s.str()); 75 } 76 return((a + b) / c); 77 } 78 79 80 81 #endif // !EXCEPTION_H
1 //main 2 #include <iostream> 3 #include "Exception.h" 4 5 //using namespace std; 6 7 int main() 8 { 9 try 10 { 11 //cout << addanddiv(-1, 2, 3) << endl;//测试异常一 12 //cout << addanddiv(2, -2, 3) << endl;//测试异常二 13 //cout << addanddiv(1, 3, -4) << endl;//测试异常三 14 cout << addanddiv(3, 2, 3) << endl; 15 } 16 catch (FirstException e) 17 { 18 printf("异常一\n"); 19 e.outputMessage(); 20 } 21 catch (SecondException e) 22 { 23 printf("异常二\n"); 24 e.outputMessage(); 25 } 26 catch (ThirdException e) 27 { 28 printf("异常三\n"); 29 e.outputMessage(); 30 } 31 return 0; 32 }