定义
异常处理是C++提供的一种捕获和处理程序错误的结构化机制。异常的常见例子有:使用new运算符无法取得所需内存、数值下标超界、运算溢出、除数为0及函数的无效参数等。发生异常后,控制不会返回异常抛出点,而由程序执行相应catch块,然后跳过所有后续catch块,恢复执行。
注意
- C++的异常出来的基本思想是将异常检测与处理分离。
- C++的异常处理是一直不唤醒机制,程序将在异常处理模块执行处理代码后继续执行。抛出异常后,调用链上的所有模块都将终止执行,称为不唤醒。
- C++的异常处理是由程序员控制的,只能处理在执行代码时出现的同步错误,不能处理由计算机硬件或运行环境引起的异步错误。
关键字
关键字 | 功能 |
---|---|
try | 放置出错时产生的异常代码 |
catch | try块后面是一个或多个catch块()称为异常处理器,每个catch块处理一种数据类型的异常 |
throw | 用于在被调用函数中抛出异常,异常匹配仅与数类型有关 |
异常处理程序
try{
//try语句块
}
catch(参数声明1){
//异常处理语句块1
}
catch(参数声明2){
//异常处理语句块2
}
catch(参数声明3){
//异常处理语句块3
}
catch(参数声明4){
//异常处理语句块4
}
catch(参数声明5){
//异常处理语句块5
}
...
注:
- 参数声明可为:类型 参数/ 类型 & 参数,类型可以是基本类型或类类型
- 若catch语句不带参数,则括号内用省略号(…)表示该catch语句可以捕获处理任意类型的异常
- 当有多个catch语句时,不带参数的catch语句应该放在最后
- 当一个catch语句块执行后,跳到所有catch块之后执行后续的语句
throw语句的一般形式
#include <iostream>
using namespace std;
double Div(double a,double b){
if(b==0)
throw 0.0;//当b=0时抛出异常
cout<<”Div Function is over.“<<endl;
return a/b;
}
void main(){
try{ //检测异常的语句
cout<<Div(1,2)<<endl;
cout<<Div(5,0)<<endl;
cout<<Div(10,3)<<endl;
}
catch(double) //捕获、处理异常的语句
{ cout<<"Divided by zero."<<endl; }
}
不同类型的异常测试
#include<iostream>
using namespace std;
int test(char *p,double e,int a){
int f =1;
try{ // 检测异常
if(*p>='0'&&*p<='9')
throw char(*p);
if(e<0||e>20000)
throw e;
if(a<18||a>70)
throw a;
}
//捕获异常
catch(char s){
f=0;
cout<<"password error:"<<s<<endl;
}
catch(double e){
f=0;
cout<<"earning error:"<<e<<endl;
}
catch(int a){
f=0;
cout<<"age error:"<<a<<endl;
}
catch(...){
f=0;
cout<<"error!"<<endl;
}
return f;
}
int main(){
char password[8];
double earnings;
int age;
cout<<"input password,earnings,age:\n";
cin>>password>>earnings,age;
if(test(password,earnings,age))
cout<<"suscessful"<<endl;
}
带异常说明的函数原型
原型 | 函数形式 |
---|---|
指定异常 | T funName(parameterList) throw(T1,T2,…,Tn); |
不抛出异常 | T funName(parameterList) throw(); |
抛出任何类型的异常 | T funName(parameterList); |
#include<iostream>
using namespace std;
void fun(int,double){
try
{ test(k,x); }
catch(int)
{ cout<<""Integer data is too large."<<endl; }
catch(double)
{ cout<<"Float data is too large."<<endl; }
}
void test(int i,double a)throw(int,double){ //指定异常
if(i>intMax) throw i;
if(a>floatMax) throw a;
}
int main(){
fun(102003,3.141590);
fun(5000,1.2e38);
}
再抛出异常传递
#include<iostream>
using namespace std;
void trigger(){
try
{ throw "WARING"; }//第一次抛出异常
catch(char *msg){//用来接收第一次抛出的异常
cout<<"trigger:"<<msg<<endl;
throw;//再次抛出异常
}
return;
}
int main(){
try
{ trigger(); }
catch(char *msg)//用来接收再次抛出的异常
{ cout<<"main:"<<msg<<endl; }
}
创建对象的异常处理
const int maxSize=1000;
template<typename T>
class Array{
public:
Array(int s);
virtual ~Array();
//其他成员函数
protected:
int size;
T *element;
}
template<typename T>Array<T>::Array(int s){ //构造函数处理异常
if(s<1||s>maxSize)
throw s;
else
element=new T[s];
}
void create(){
int size();
try{
cin>>size;
Array<int> IntAry(size);
}
catch(int s)
{ //处理异常 }
}