c++学习笔记七(异常)

这篇博客详细介绍了C++中的异常处理机制,包括在构造函数和成员函数中抛出异常,以及如何进行异常匹配。通过示例展示了标准异常类和自定义异常类的使用,并提及了C++11与C++98在自定义异常声明上的差异。异常处理后,程序会继续执行catch块之后的代码。
摘要由CSDN通过智能技术生成

在这里插入图片描述
在这里插入图片描述
注意:虽然异常后的代码不会执行,但是处理(catch)后的程序会继续执行
在这里插入图片描述
示例:

#include <iostream>
using namespace std;

int divide(int a,int b){
    if(0==b) throw string("Error:除数不能为0!");			//抛出异常
    return a/b;
}

int main(){
    int a,b;
    cin >> a >> b;

    try{
        cout << a << '/' << b << '=' << divide(a,b) <<endl;
    }
    catch (string s){									//捕获异常
        cout << s <<endl;							//catch处理之后,如果底下还有代码,处理之后会继续
    }												//执行下去的
}

示例二(构造函数抛出异常):

#include <iostream>
using namespace std;

class Array{
    int* data;
public:
    Array(int n){
        if(n<=0)    throw string("Arrary size not <= 0!");	//构造函数抛出异常不会调用析构函数
        data = new int[n];									//因为出现异常后,构造都没有进行完成,
    }														//所以都用不到析构函数
    ~Array(){
        cout << __func__ << endl;
        delete [] data;
    }
};

void test(){
    int n;
    cin >> n;
    Array Array(n);
}

int main(){
    try{
        test();
    }
    catch (string s){
        cout << "Error:" << s << endl;
    }
}

示例三(成员函数抛出异常):

#include <iostream>
using namespace std;

class Array{
    int* data;
    int si
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值