在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);
}