Part12 异常处理 12.2异常处理中的构造与析构

自动的析构
找到一个匹配的catch异常处理后
  初始化异常参数。
  将从对应的try块开始到异常被抛掷处之间构造(且尚未析构)的所有自动对象进行析构。
  从最后一个catch处理之后开始恢复执行。

 

//例12-2 带析构语义的类的C++异常处理
#include<iostream>
#include<string>
using namespace std;
class MyException{
public:
    MyException(const string &message) : message(message){}
    ~MyException() {}
    const string &getMessage() const {return message;}
private:
    string message;
};

class Demo{
public:
    Demo() {cout << "Constructor of Demo" << endl;}
    ~Demo() {cout << "Destructor of Demo" << endl;}
};
void func() throw (MyException){
    Demo d;
    cout << "Throw MyException in func()" << endl;
    throw MyException("exception thrown by func()");
}
int main(){
    cout << "In main function" << endl;
    try{
        func();
    }catch(MyException& e){
        cout << "Caught an exception: " << e.getMessage() << endl;
    }
    cout << "Resume the execution of main()" << endl;
    return 0;
}

 

posted @ 2018-01-11 03:31  LeoSirius  阅读(110)  评论(0编辑  收藏  举报