《More Effective C++》——异常(Exceptions)

《More Effective C++》——异常(Exceptions)

More Effective C++ Exceptions.png

条款11:禁止异常(exceptions)流出destructors之外

下面是这节说的导致程序terminate异常情况的demo:

// exceptions
#include <iostream>
using namespace std;

class Session {
    public:
        Session() {
            logCreation(this);
        }
        ~Session() {
            logDestruction(this);//an uncaught exception occurs
        }
    private:
        static void logCreation(Session *objAddr) {
            cout << "Create " << objAddr << '\n';
        }
        static void logDestruction(Session *objAddr) {
            cout << "Destroy " << objAddr << '\n';
            cout << "Throw an exception in" << objAddr << '\n';
            throw 21;
        }
};

void on_terminate(){
 cout << "terminate function called!" << endl;
 return;
}

void test() {
    Session s;
    try {
        throw 20;
    } catch (int e) {
        cout << "An exception occurred. Exception Nr. " << e << '\n';
    }
}

int main () {
    set_terminate(on_terminate);
    test();
    cout<<"terminate function not called!"<<endl;
    return 0;
}

main函数中首先抛出了异常,导致Session对象析构,logDestruction被调用,抛出异常21,而析构函数没有捕获这个异常,而是让它流出了destructor以外,而此时异常20正在作用,C++会调用terminate函数,程序终止:

Create 0x7646678d3c4d
An exception occurred. Exception Nr. 20
Destroy 0x7646678d3c4d
Throw an exception in0x7646678d3c4d
terminate function called!

如果在析构函数中try-catch

~Session() {
    try {
        logDestruction(this);
    } catch (int e) {
        cout << "An exception occurred. Exception Nr. " << e << '\n';
    }
}

则程序正常执行完毕:

Create 0x7cae77ecf33d
An exception occurred. Exception Nr. 20
Destroy 0x7cae77ecf33d
Throw an exception in0x7cae77ecf33d
An exception occurred. Exception Nr. 21
terminate function not called!

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券