64-C++中的异常处理(上)

来源:互联网 发布:java windows 路径 编辑:程序博客网 时间:2024/06/05 02:47

1、C++异常处理

这里写图片描述

2、

这里写图片描述

#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;}Divided by zero...

3、

这里写图片描述

4、

这里写图片描述

5、

这里写图片描述

6、

这里写图片描述
通过throw抛出的异常,有对应的catch来捕获,严格按要求来匹配,
异常只能被捕获一次,
catch(…)为捕获所有异常,必须放在所有catch的最后一个位置上。
当没有捕获异常时要向上一级传,直到被处理为止。
当在try中抛出多个异常时,只捕获最后一个异常。

#include <iostream>#include <string>using namespace std;void Demo1(){    try    {           throw '1';        throw 1;//只捕获最后一个异常    }    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(int c)    {        cout<<"catch(int c)"<<endl;     }    catch(...)//只能放在最后一个catch位置    {        cout << "catch(...)" << endl;    }}void Demo2(){    throw string("D.T.Software");    //throw "D.T.Software"; 抛出 const char *类型}int main(int argc, char *argv[]){        Demo1();    try    {        Demo2();    }    catch(char* s)    {        cout << "catch(char *s)" << endl;    }    catch(const char* cs)    {        cout << "catch(const char *cs)" << endl;    }    catch(string ss)    {        cout << "catch(string ss)" << endl;    }    return 0;}catch(int c)catch(string ss)

7、小结

这里写图片描述