注意: throw 抛出异常,catch 捕获异常,try 尝试捕获异常
catch 中的参数类型要和throw 抛出的数据类型一致
try
{
//可能抛出异常的语句
}
catch (异常类型1)
{
//异常类型1的处理程序
}
catch (异常类型2)
{
//异常类型2的处理程序
}
// ……
catch (异常类型n)
{
//异常类型n的处理程序
}
例1:
#include <iostream>
#include <stdlib.h>
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];
}
这是用来处理数组越界的代码,throw 抛出的是枚举型的数据,因此catch 中的数据类型也是相应的枚举型
C++语句中有默认的异常处理函数,会对异常做出处理。
浙公网安备 33010602011771号