一、C++语言异常处理的实现
1.三个保留字
try
{
}
catch(异常类型1 参数1)
{
}
# include <iosteam>
using namesapce
void aa()
{
cout<<"这是由用户指定的错误处理函数"<<endl;
exit(-1);
}
void main()
{
set_terminate(aa);
try
{
throw"error";
}
catch(int){}
}
2.实例
# include <iosteam>
double divide(duoble,double);
void main()
{
double f1 = 0.0, f2 = 0.0;
try
{
cout<<"f1/f2="<<divide(f1,f2)<<"\n";
}
catch(double)
{
cout<<"被0除"<<"\n";
}
}
double divide(double x, double y)
{
if(y==0)throw 0.0;
return x/y;
}
# include <iosteam>
using namespace std;
void detail(int k);
{
cout<<"Start of detail function.\n";
if(k==0) throw 123;
cout<<"End of detail function.\n"
}
void compute(int i)
{
cout<<"Start of compute function.\n";
detail(i);
cout<<"End of compute function.\n";
}
int main()
{
int x;
cout<<"Enter x(0 will throw an exception):";
cin>>x;
try
{
compute(x);
}
catch(int i)
{
cout<<"Exception:"<<i<<endl;
}
cout<<"The end.\n";
return 0;
}
# include<iosteam>
using namespace std;
void main()
{
int i;
char ch;
cout<<"请输入一个整数和一个字符\n";
try
{
cin>>i>>ch;
if(i==0)throw 0;
if(ch=='!')throw '!';
}
catch(int)
{
cout<<"输入为0\n";
}
catch(char)
{
cout<<"输入字符!"<<endl;
}
cout<<"程序结束"<<endl;
}
# include <iosteam>
using namespace std;
class OutOfBounds
{
public:
OutOfBounds(int a)
{
i=a;
}
int indexValue()
{
return i;
}
private:
int i;
};
class Array
{
public:
int &operator[](int i)
{
if(i<0||i>=10)
throw OutOfBounds(i);
return a[i];
}
private:
int a[10];
};
void main()
{
Array a;
try
{
a[3]=30;
cout<<"a[1000]"<<a[1000]<<endl;
}
catch(OutOfBounds error)
{
cout<<"Subscript value"<<error.indexValue()
cout<<"Out of bounds.\n";
}
return;
}
二、重新抛出异常和异常规范
1.重新抛出异常
# include <iosteam>
using namespace std;
void h()
{
throw 0;
}
void g()
{
try
{
h();
}
catch
{
cout<<"Catch in a\n";
throw;
}
}
int main()
{
try
{
g();
}
catch(int)
{
cout<<"Catch in main\n";
}
return 0;
}
2.异常规范
//如果程序运行时,函数抛出了一个没有被列在它的异常规范中的异常时
//系统调用C++标准库中定义的函数unexcepted(),而unexception()
//调用terminate()终止整个程序的运行
void f() throw(X,Y)
{
...
}
//函数f只能抛出X、Y异常,throw(X,Y)称为异常规范
//如果写成throw(),则表示不会抛出异常
三、C++标准库中的异常类
length_error
domain_error
out_of_range_error
invalid_argument
range_error
overflow_error
underflow_error
# include<exception>
# include<iosteam>
using namesapce std;
void main()
{
try
{
exception theError;
throw(theError);
}
catch(const exception &theError)
{
cout<<theError.what()<<endl;
}
try
{
logic_error theLogicError("Logic Error!");
throw(theLogicError);
}
catch(const exception theLogicError)
{
cout<<theLogicError.what()<<endl;
}
}
Unknown exception
Logic Error