c++初级 之 异常处理trycatchthrow

以下为例

demo.cpp

#include"Exception.h"
#include"IndexException.h"
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;

void test(int a)
{
	if(a == 0)throw int(1);//用这种写法,类型(类型的初始化值)
	if(a == 1)throw new IndexException;//抛的指针
	if(a == 2)throw IndexException();//抛对象
	if(a == 3)throw string("出错啦");
	throw 'k';
}

int main()
{
	try{//trycatch的句型一般都是在main函数中使用,不会用在类等等里面
		int a = 0;
		for(;a<5;a++){//会发现根本不执行循环,因为执行完catch块后直接继续catch后程序,不会回到try里面
			test(a);
		}
	}
	catch(int &e){     //这样就可以对throw的值进行不变值操作比如打印出来之类的了
		cout << e << endl;
		cout << "int_Exception" << endl;
	}
	catch(Exception *p){
		p->printException();
		delete p;//记得释放堆内存,否则结果里不会有调用析构函数的那两行
		p = NULL;
	}
	catch(Exception &a){
		a.printException();
		cout << "Exception &a" << endl;
	}//catch块执行完后会自动调用析构函数(结果中有显示),释放栈内存
	catch(string &str){
		cout << str << endl;
	}
	catch(...){//其余情况。若没有这个,就有抛出异常不被catch而导致系统崩亏的风险
		cout << "exception" << endl;
	}
	system("pause");
	return 0;
}

将总的异常定义为接口类Exception.h

#ifndef EXCEPTION_H
#define EXCEPTION_H
//接口类只含有纯虚函数(除构造函数和虚析构函数外)
class Exception
{
public:
	virtual void printException() = 0;
	virtual ~Exception();
};



#endif

Exception.cpp

#include"Exception.h"
#include<iostream>
using namespace std;


Exception::~Exception()
{
	cout << "Exception::~Exception()" << endl;
}//不是一定要写的,这里只是为了可视。为了防止内存泄露,在声明中给析构函数添加virtual字样就好,具体实现可以为空

具体的某种异常(比如下标异常)定义为接口类的子类IndexExceptio.h

#ifndef INDEXEXCEPTION_H
#define INDEXEXCEPTION_H
#include"Exception.h"
class IndexException:public Exception
{
public:
	virtual void printException();
	virtual ~IndexException();
};









#endif

IndexException.cpp

#include"IndexException.h"
#include<iostream>
using namespace std;

void IndexException::printException()
{
	cout << "下标越界" << endl;
}

IndexException::~IndexException()
{
	cout << "IndexException::~IndexException()" << endl;
}

运行结果如下:

a=0时

a=1

(如果没有delete,那就只有一句 下标越界)

a=2

a=3

a=4


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值