C++异常处理

2017-08-24  本文已影响24人  第八区

要点

示例代码

#include "stdafx.h"
#include "iostream"
#include "string.h"
using namespace std;
#pragma warning(disable : 4996)  
class ExceptionA {
private:
    char *msg;
public:
    ExceptionA(const char *msg) {
        cout << "构造" <<msg<< endl;
        if (msg == NULL) {
            this->msg = NULL;
        }else{
            this->msg = new char[strlen(msg) + 1];
            strcpy(this->msg, msg);
        }
    }
    char * getMsg()const {
        return this->msg;
    }
    ExceptionA(const ExceptionA& e) {
        cout << "拷贝构造" << endl;
        if (this->msg == NULL) {
            delete[]this->msg;
        }
        this->msg = new char[strlen(e.getMsg()) + 1];
        strcpy(this->msg, e.getMsg());
    }
    ~ExceptionA() {
        cout << "析构" << msg << endl;
        if (this->msg != NULL) {
            delete[]this->msg;
        }
    }
};

void funcA(int x) {

    switch (x)
    {
    case 0:{
        //throw异常后,temp1会自动析构,而temp不会自动析构和释放
        ExceptionA *temp = new ExceptionA("temp");
        ExceptionA temp1("temp1");
        throw 1;
    }
        break;
    case 1:
        throw 'a';
        break;
    case 2:
        //可以直接接受或使用引用接收。推荐使用引用接收
        throw(ExceptionA("msg 2"));
        break;
    case 3:
        //抛出指针,但对象会被清理。catch到的指针是野指针
        throw(&ExceptionA("msg 3"));
        break;
    case 4: {
        //抛出动态分配的指针。catch到后使用完后需要delete
        ExceptionA* e = new ExceptionA("msg4");
        throw(e);
    }
        break;
    case 5:
        throw 3.14f;
    case 6:
        throw 3.14;
    }
    cout << "funcA success " << x << endl;
}

void funcB(int index) throw(float ,double){
    try {
        funcA(index);
    }
    catch (int e) {
        cout << "catch int " << e << endl;
    }
    catch (char e) {
        cout << "catch char " << e << endl;
    }
    catch (ExceptionA e) {
        cout << "catch  ExceptionA " << e.getMsg() << endl;
    }
    //使用对象接收和使用对象的引用接收不能同时存在。
    //catch (ExceptionA &e) {
    //  cout << "catch  ExceptionA & " << e.getMsg() << endl;
    //}
    catch (ExceptionA *e) {
        cout << "catch  ExceptionA * " << e->getMsg() << endl;
        delete e;
    }
    catch (float e) {
        //接续向上抛出异常
        cout << "catch float and throw  " << e << endl;
        throw e;
    }
    catch (double e) {
        //接续向上抛出异常,但函数的方法上有限制可以抛出异常的类型。这里会出错
        cout << "catch double and throw  " << e << endl;
        throw e;
    }
}
int main()
{
    try {
        funcB(6);
    }
    catch (float e) {
        cout << "main catch " << e << endl;
    }
    return 0;
}

异常处理场景演示

上一篇 下一篇

猜你喜欢

热点阅读