C++异常处理(try和catch)

在C++中,一个函数能够检测出异常并且将异常返回,这种机制称为抛出异常。当抛出异常后,函数调用者捕获到该异常,并对该异常进行处理,我们称之为异常捕获
       C++新增throw关键字用于抛出异常,新增catch关键字用于捕获异常,新增try关键字尝试捕获异常。通常将尝试捕获的语句放在 try{ } 程序块中,而将异常处理语句置于 catch{ } 语句块中。

基本语法:

 throw 表达式;
抛出异常由throw关键字加上一个表达式构成。抛出异常后需要捕获异常以及异常处理程序,其基本语法如下:
try
{
    //可能抛出异常的语句
}
catch (异常类型1)
{
    //异常类型1的处理程序
}
catch (异常类型2)
{
    //异常类型2的处理程序
}
// ……
catch (异常类型n)
{
    //异常类型n的处理程序
}

#include<iostream>
using namespace std;

enum index{underflow, overflow};

int array_index(int *A, int n, int index);

int main()
{
    int *A = new int[10];
    for(int i=0; i<10; i++)
        A[i] = i;
    try
    {
        cout<<array_index(A,10,5)<<endl;
        cout<<array_index(A,10,-1)<<endl;
        cout<<array_index(A,10,15)<<endl;
    }
    catch(index e)
    {
        if(e == underflow)
        {
            cout<<"index underflow!"<<endl;
            exit(-1);
        }
        if(e == overflow)
        {
            cout<<"index overflow!"<<endl;
            exit(-1);
        }
    }

    return 0;
}

int array_index(int *A, int n, int index)
{
    if(index < 0) throw underflow;
    if(index > n-1) throw overflow;
    return A[index];
}

在前面我们介绍了new和delete动态分配内存操作符,如果new或new[]不能成功分配所请求的,将会抛出一个bad_alloc异常。在使用new或new[]操作符分配动态内存,可以通过如下方式检测并捕获存储空间分配失败的异常。

int * p;
try
{
    p = new int[10];
}
catch(bad_alloc)
{
    cerr<<"allocate failure!"<<endl;
    exit(-1);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello Jason

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值