码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 异常对象

时间:2015-04-12 12:02:30      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

程序运行结果如下:

技术分享

C++ 异常对象

标签:

原文地址:http://blog.csdn.net/sxhlovehmm/article/details/45008735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!