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

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、小结

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值