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触发了一个断点  有中断和继续的按钮,按中断会跑到一段代码,按继续窗口消失

按忽略窗口也消失


 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值