C++编程思想 第2卷 第1章 异常处理 异常匹配 不捕获异常 set_terminate()函数

通过使用标准的set_terminate()函数,可以设置读者自己的terminate()函数,
set_terminate()返回被替换的指向terminate()函数的指针,这样就可以在
需要的时候恢复原来的terminate()

set_terminate()函数的返回值被保存下来并且被还原,使得terminate()
函数可以用来帮助隔离产生不可捕获的异常的代码块

//: C01:Terminator.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.
// Use of set_terminate(). Also shows uncaught exceptions.
#include <exception>
#include <iostream>
using namespace std;

void terminator() {
  cout << "I'll be back!" << endl;
  exit(0);
}

void (*old_terminate)() = set_terminate(terminator);

class Botch {
public:
  class Fruit {};
  void f() {
    cout << "Botch::f()" << endl;
    throw Fruit();
  }
  ~Botch() { throw 'c'; }
};

int main() {
  try {
    Botch b;
    b.f();
  } catch(...) {
    cout << "inside catch(...)" << endl;
  }
  getchar();
} ///:~

old_terminate 创建了一个指向函数的指针,而且用set_terminate()函数可以用来帮助隔离产生不可捕获的异常的代码块
的返回值初始化这个指针。

类Botch不仅在函数f()中抛出异常,而且在析构函数中也抛出异常

无输出

其实有输出

要把 exit(0); 给注释掉 不然就算是getchar()也是暂停不了屏幕的

输出

Botch::f()
I'll be back!

终止 重试 忽略

终止黑框窗口就关闭了

重试 就显示一个对话框 exe触发了一个断点  有中断和继续的按钮,按中断会跑到一段代码,按继续窗口消失

按忽略窗口也消失


 

猜你喜欢

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