c++ primer 异常处理(1)学习记录

1. throw语句和catch语句基本用法示例示例
throw语句用于让开发者人工抛出异常,catch语句捕捉抛出的异常,来继续执行程序

#include<iostream>
#include<vector>
using namespace std;
int main(int argc, char const *argv[])
{
    double m,n;
    cin >> m>>n;
    try{
        cout << "before dividing." << endl;
        if(n == 0){
            throw -1;
        }
        else
        {
            cout << m/n << endl;
        }
        cout << "after dividing." << endl;
    }
    catch(double d){
        cout << "catch(double)" << d <<endl;
    }
    catch(int e){
        cout << "catch(int)" <<e<<endl;
    }
    //throw出的异常如果被捕捉,try块立即停止执行,程序就会进入catch语句继续执行
    //否则直接结束
    cout << "finished" << endl;
    
    return 0;
}

2.在main()函数内部来抛出异常

#include<iostream>
#include<vector>
using namespace std;

class CException{
public:
    string msg;
    CException(string s):msg(s) {}
};

double Divide(double x,double y){
    if(y == 0)
        throw CException("error:divided by zero.");
    cout << "in divide" << endl;
    return x / y;
}

int count_tax(int salary){
    try
    {
        if(salary < 0)
            throw -1;//抛出异常后后面的语句不再执行
        cout << "counting tax" << endl;
    }
    catch(int)
    {
        cout << "salary <0" << endl;
    }
    cout << "tax counted" << endl;
    return salary*0.5;
}

int main(){
    double f = 1.2;
    try{
        count_tax(-1);//count_tax会自行处理异常,不会抛给main()函数,所以main()函数不会立即终止
        f = Divide(3,0);//Divide函数抛出了异常,会交给main()函数处理
        cout << "end of try block" << endl;
    }
    catch(CException e){
        cout << e.msg <<endl;
    }
    cout << "f=" << f << endl;
    cout << "finished" << endl;
    return 0;
}

3. 提示信息

int count_tax(int salary){
    try
    {
        if(salary < 0)
            throw "zero salary";//抛出异常后后面的语句不再执行
        cout << "counting tax" << endl;
    }
    catch(string s)
    {
        cout << "error:salary <0" << endl;
        //用cout给出error信息
    }
    cout << "tax counted" << endl;
    return salary*0.5;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值