1.catch子句参数为对象
先看一段代码:
#include <iostream>
#include <exception>
using namespace std;
class MyException :public exception{
public:
MyException(){
cout<<"MyException()"<<endl;
}
~MyException(){
cout<<"~MyException()"<<endl;
}
MyException(const MyException& rhs){
cout<<"MyException(const MyException& rhs)"<<endl;
}
void what(){
cout<<"MyException what()"<<endl;
}
};
class DerivedException:public MyException{
public:
DerivedException(){
cout<<"DerivedException()"<<endl;
}
~DerivedException(){
cout<<"~DerivedException()"<<endl;
}
//派生类如果不显示调用基类的拷贝构造函数,则会隐式得调用基类的默认构造函数
DerivedException(const DerivedException& rhs):MyException(rhs){
cout<<"DerivedException(const DerivedException& rhs)"<<endl;
}
void what(){
cout<<"DerivedException what()"<<endl;
}
};
void ExceptionTest(){
try{
throw DerivedException();//这不是一个局部对象,并不会随着ExceptionTest()的退栈而销毁
}catch(MyException ex){
ex.what();
throw; //重新抛出的是原来的异常对象;没有更改过的。
}
}
int main(){
try{
ExceptionTest();
}catch(DerivedException ex){
ex.what();
}
return 0;
}
程序运行结果:
2.当catch子句为引用参数
代码如下:
#include <iostream>
#include <exception>
using namespace std;
class MyException :public exception{
public:
MyException(){
cout<<"MyException()"<<endl;
}
~MyException(){
cout<<"~MyException()"<<endl;
}
MyException(const MyException& rhs){
cout<<"MyException(const MyException& rhs)"<<endl;
}
void what(){
cout<<"MyException what()"<<endl;
}
};
class DerivedException:public MyException{
public:
DerivedException(){
cout<<"DerivedException()"<<endl;
}
~DerivedException(){
cout<<"~DerivedException()"<<endl;
}
//派生类如果不显示调用基类的拷贝构造函数,则会隐式得调用基类的默认构造函数
DerivedException(const DerivedException& rhs):MyException(rhs){
cout<<"DerivedException(const DerivedException& rhs)"<<endl;
}
void what(){
cout<<"DerivedException what()"<<endl;
}
};
void ExceptionTest(){
try{
throw DerivedException();//这不是一个局部对象,并不会随着ExceptionTest()的退栈而销毁
}catch(MyException &ex){
ex.what();
throw; //如果对ex做出改变,则改变会被繁殖到下一个catch子句中
}
}
int main(){
try{
ExceptionTest();
}catch(DerivedException &ex){
ex.what();
}
return 0;
}
程序运行结果如下: