c++初级 之 异常处理trycatchthrow

来源:互联网 发布:杰科网络电视机顶盒t2 编辑:程序博客网 时间:2024/05/18 03:35

以下为例

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


原创粉丝点击