C++编程思想 第2卷 第1章 异常处理 清理

异常处理的魅力之一在于程序能够从正常的处理流程中跳转到恰当的异常
处理器中。如果异常抛出时,程序不做恰当的清理工作,那么异常处理本身
并没有什么用处

当构造函数没有正常结束时不会调用相关联的析构函数

//: C01:Cleanup.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Exceptions clean up complete objects only.
#include <iostream>
using namespace std;

class Trace {
  static int counter;
  int objid;
public:
  Trace() {
    objid = counter++;
    cout << "constructing Trace #" << objid << endl;
    if(objid == 3) throw 3;
  }
  ~Trace() {
    cout << "destructing Trace #" << objid << endl;
  }
};

int Trace::counter = 0;

int main() {
  try {
    Trace n1;
    // Throws exception:
    Trace array[5];
    Trace n2;  // Won't get here.
  } catch(int i) {
    cout << "caught " << i << endl;
  }
  getchar();
} ///:~

类Trace对象踪迹,它用一个静态数据成员counter来统计已经创建的对象
的个数,而用普通数据成员objid来追踪特定对象的编号

main函数首先创建一个单独的对象n1(objid 0),然后试图创建一个具有5个
Trace对象的数组,但是,在第四个对象被完整创建之前抛出了一个异常。
对象n2根本就没有创建

输出
constructing Trace #0
constructing Trace #1
constructing Trace #2
constructing Trace #3
destructing Trace #2
destructing Trace #1
destructing Trace #0
caught 3

对象数组的三个元素成功创建了,但是在创建第四个对象数组元素的过程
中构造函数抛出了一个异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值