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

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

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81569726