1.c++的异常处理
c++内置了异常处理的语法元素try…catch
—-try语句处理正常代码逻辑
—-catch语句处理异常情况
—-try语句中的异常由对应的catch语句处理
try{double r = divide(1,0);}catch(...){cout << "Divide by zero"<< endl;}
2.抛出异常
c++通过throw语句抛出异常信息
double divide(double a,double b){const double delta = 0.0000000000001;double ret = 0;if(!((-delta<b)&&(b<delta))){ret = a / b;}else{throw 0; //产生0异常}return 0;}
3.c++异常处理分析
—-throw抛出的异常被catch处理
当前函数能够处理异常,程序继续往下执行
当前函数无法处理异常,则函数停止执行并返回

#include <iostream>#include <string>using namespace std;double divide(double a, double b){const double delta = 0.000000000000001;double ret = 0;if( !((-delta < b) && (b < delta)) ){ret = a / b;}else{throw 0;}return ret;}int main(int argc, char *argv[]){try{double r = divide(1, 0);cout << "r = " << r << endl;}catch(...){cout << "Divided by zero..." << endl;}return 0;}
同一个try语句可以跟上多个catch
—-catch语句可以定义具体要定义的异常类型
—-不同类型的异常由不同的catch语句负责处理
—-try语句中可以抛出任何类型的异常
—-catch(…)用于处理所有类型的异常
—-任何异常都只能被捕获(catch)一次
#include <iostream>#include <string>using namespace std;void Demo1(){try{throw 'c';}/*catch(...) //should be placed at the last place{}*/catch(char c){cout << "catch(char c)" << endl;}catch(short c){cout << "catch(short c)" << endl;}catch(double c){cout << "catch(double c)" << endl;}catch(...){cout << "catch(...)" << endl;}// catch(int c)///{// cout << "catch(int c)" << endl;//}}void Demo2(){// throw "D.T.Software"; //type is const char*,can't be catched;type should be the samethrow string("D.T.Software");}int main(int argc, char *argv[]){Demo1();try{Demo2();}catch(const char* s){cout << "catch(const char *s)" << endl;}catch(string ss){cout << "catch(string ss)" << endl;}return 0;}
小结:
1.c++中直接支持异常处理的概念
2.try…catch…是c++中异常处理的专用语句
3.try语句处理正常的代码逻辑,catch语句处理异常情况
4.同一个try语句可以跟上多个catch语句
5.异常处理必须严格匹配,不进行任何类型转换
