C++ 异常对象

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;
}

程序运行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值