.最简单的异常CPP实现
1 /* 纯CPP异常 */ 2 3 #include<iostream> 4 #include<cstring> 5 6 using namespace std; 7 8 // try 存放有可能触发异常的程序 9 // throw 抛出异常 终止当前代码块继续执行 避免程序崩溃 throw可以抛出任何类型的对象 包括基本数据类型 10 // catch 每一个catch处理一个类型 catch内部可以细化处理每一个异常,避免出错 11 12 13 14 // 抛出一个整数 15 double divv(int x,int y) 16 { 17 try 18 { 19 if(y==0) 20 { 21 throw 1;// 抛出以后不会执行 22 } 23 else if () 24 { 25 throw 2;// 抛出以后不会执行 26 } 27 cout << "已经执行除法" << endl; 28 return x*1.0/y; 29 } 30 catch (int code) 31 { 32 if(code == 1) 33 { 34 cout << "被除数为0" << endl; 35 } 36 else if (code == 2) 37 { 38 cout << "除数为0" << endl; 39 } 40 cout << "没有执行除法" << endl; 41 return -1.0;// 代表错误 42 } 43 44 } 45 46 47 void main() 48 { 49 int x,y; 50 cin >> x >> y;// 输入初始化x,y 51 52 cout << "x = " << x << endl; 53 cout << "y = " << y << endl; 54 cout << "x/y = " << divv(x,y) << endl; 55 56 57 cin.get(); 58 } 59 60 61 62 //--------------------------------------------------------- 63 64 // 抛出一个字符串 65 double divvstr(int x,int y) 66 { 67 try 68 { 69 if(y==0) 70 { 71 throw "STR小伙子你输入的被除数为0";// 抛出以后不会执行 72 } 73 else if (x == 0) 74 { 75 throw "STR小伙子你输入的除数为0";// 抛出以后不会执行 76 } 77 cout << "继续执行" << endl;// throw 之后,后面的语句无论如何不会执行 78 79 80 return x*1.0/y; 81 } 82 catch (const char * errorstr) 83 { 84 if (strcmp(errorstr,"STR小伙子你输入的被除数为0")) 85 { 86 cout << errorstr << endl; 87 } 88 else if (strcmp(errorstr,"STR小伙子你输入的除数为0") 89 { 90 cout << errorstr << endl; 91 } 92 93 cout << "异常结束" << endl; 94 return -1;// 设定的返回值必须返回,不然读取内存中的垃圾值 95 } 96 97 } 98 99 double divvstr(int x,int y) 100 { 101 if (y == 0) 102 { 103 return -1; 104 } 105 else 106 { 107 // 没有返回值会读取垃圾值 108 } 109 110 } 111 112 void main() 113 { 114 int x,y; 115 cin >> x >> y;// 输入初始化x,y 116 117 cout << "x = " << x << endl; 118 cout << "y = " << y << endl; 119 cout << "x/y = " << divvstr(x,y) << endl; 120 121 122 cin.get(); 123 } 124 125 //------------------------------------------------------------------- 126 127 // 抛出一个类的对象 128 129 class errorclass 130 { 131 int num; 132 }; 133 134 class errorclassA 135 { 136 137 }; 138 139 double divvclass(int x,int y) 140 { 141 try 142 { 143 errorclass e1;// 根据类型 144 throw e1; 145 return x*1.0/y; 146 } 147 catch (errorclass e1) 148 { 149 cout << typeid(e1).name() << endl; 150 151 return -1.0; 152 } 153 154 catch (errorclassA e1)// 每一个catch处理一个类型 155 { 156 //if else 判断某个类型对象内部的值 157 158 cout << typeid(e1).name() << endl; 159 160 return -1.0; 161 } 162 163 } 164 165 void main() 166 { 167 int x,y; 168 cin >> x >> y;// 输入初始化x,y 169 170 cout << "x = " << x << endl; 171 cout << "y = " << y << endl; 172 cout << "x/y = " << divvclass(x,y) << endl; 173 174 175 cin.get(); 176 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-06-16 09:39 Dragon-wuxl 阅读(196) 评论(0) 收藏 举报
浙公网安备 33010602011771号