程序抛出异常有很多情况,例如0操作数、非法参数值、非法输入值、数组下标越界等。这篇文章主要是对c++的抛出异常、捕获异常和异常处理,并自定义异常类型。
1.抛出异常:
int Calculation(int a,int b,int c){
if(c == 0){
throw "ERROR:The divisor should be greater than 0";
}
return a + b / c;
}
在本例程序中,使用了throw关键字进行异常的抛出,当被除数等于0时,程序抛出异常。
2.捕获异常和异常处理
int Calculation(int a,int b,int c){
if(c == 0){
throw "ERROR:The divisor should be greater than 0";
}
return a + b / c;
}
int main(int argc,char *argv[]){
try{cout<<Calculation(2,1,0)<<endl;}
catch(char const* e){
cout<<"An exception has been thrown"<<endl;
cout<<e<<endl;
return -1;
}
return 0;
}
在这段代码中,抛出的异常有包含这段代码的try块进行处理。紧跟着在try块之后是catch块。每个catch块都有一个参数,参数的类型决定了这个catch块要捕捉异常的类型。由于在函数中throw了一句话,所以在try执行代码后,后面的catch将对异常进行捕获,其类型为const char*。catch块中的代码是包含了异常改正之后所恢复的代码。如果不能恢复,则进行错误信息提示。
3.自定义异常类
尽管C++提供很多诸如bad_alloc、bad_typeid、char、int等异常类型,但在实际开发中,通常要自定义异常类。下面这段代码将演示一个简单的异常类:
#include<iostream>
#define Error -1
using namespace std;
class Customized_Exceptions{
public:
Customized_Exceptions():
message("ERROR!"){
}
Customized_Exceptions(char* theMessage){
message = theMessage;
}
void output(){
cout<<message<<endl;
}
private:
string message;
};
template<class T>
T Calculation(T a,T b,T c){
if(c == 0){
throw Customized_Exceptions("ERROR:The divisor should be greater than 0");
}
return a + b / c;
}
int main(int argc,char* argv[]){
try{
cout<<Calculation(2,1,0);
}
catch(Customized_Exceptions error){
cout<<"An exception has been thrown"<<endl;
error.output();
return Error;
}
return 0;
}
在被除数=0时,抛出了一个自定义异常类型Customized_Exceptions,并赋值类中的message为"ERROR:The divisor should be greater than 0"。catch代码块捕获异常类型并进行异常处理。