前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >《More Effective C++》——异常(Exceptions)

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

原创
作者头像
jackieluo
发布2019-07-25 14:20:05
4660
发布2019-07-25 14:20:05
举报
文章被收录于专栏:Jackie技术随笔

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

More Effective C++ Exceptions.png
More Effective C++ Exceptions.png

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

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

代码语言:txt
复制
// 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函数,程序终止:

代码语言:txt
复制
Create 0x7646678d3c4d
An exception occurred. Exception Nr. 20
Destroy 0x7646678d3c4d
Throw an exception in0x7646678d3c4d
terminate function called!

如果在析构函数中try-catch

代码语言:txt
复制
~Session() {
    try {
        logDestruction(this);
    } catch (int e) {
        cout << "An exception occurred. Exception Nr. " << e << '\n';
    }
}

则程序正常执行完毕:

代码语言:txt
复制
Create 0x7cae77ecf33d
An exception occurred. Exception Nr. 20
Destroy 0x7cae77ecf33d
Throw an exception in0x7cae77ecf33d
An exception occurred. Exception Nr. 21
terminate function not called!

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 《More Effective C++》——异常(Exceptions)
    • 条款11:禁止异常(exceptions)流出destructors之外
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档