为什么我们需要一个函数try块? [英] Why do we need a function try block?

查看:243
本文介绍了为什么我们需要一个函数try块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是的后续问题帖子

问题:如果一个函数try块没有处理抛出的异常在构造函数中,为什么我们需要它们呢?

Question: If a function try block does not "handle" the exception raised in the constructor, why do we need them after all? Could you give an example taking advantage of function try block?

考虑下面的代码。

#include <iostream>
#include <new>  
#include <exception>
using namespace std;

struct X {
  int *p;
  X() try : p(new int[10000000000]) {}
  catch (bad_alloc &e) {
    cerr << "exception caught in the constructor: " << e.what() << endl;
  }
};

int main() {
  try {
    X x;
  }
  catch (exception &e){
    cerr << "exception caught outside the constructor: " << e.what() << endl;
  }
  return 0;
}

输出为

异常捕获在构造函数中:std :: bad_alloc
异常捕获在构造函数之外:std :: bad_alloc

在我看来,无论我在try块中做什么,异常总是被抛出到外部范围,调用构造函数,例如 X x;

It seems to me that, no matter what I do in the function try block, the exception is always going to be thrown to the outer scope which calls the constructor, e.g. the X x; in the above code.

function try block的定义,摘自C ++ Primer 5th。

Definition of "function try block", excerpted from "C++ Primer 5th."


要处理构造函数初始化器中的异常,我们必须将构造函数写为函数try块。函数try块允许我们将一组catch子句与构造函数的初始化阶段(或析构函数的销毁阶段)以及构造函数(或析构函数)的函数体相关联。

To handle an exception from a constructor initializer, we must write the constructor as a function try block. A function try block lets us associate a group of catch clauses with the initialization phase of a constructor (or the destruction phase of a destructor) as well as with the constructor’s (or destructor’s) function body.


推荐答案

这是正确的例外总是传播。

You're right that the exception is always propagated.

函数try块可以捕获异常,例如破坏一个作为参数传递的对象(也许这是一个智能指针类?),而不引入一个人为的基类。

The function try block enables you to catch that exception and e.g. destroy an object passed as argument (maybe this is a smart pointer class?), without introducing an artificial base class.

更广泛地说,

对于构造函数的情况:

对于所有成功构造的子对象(包括基类子对象(如果有))调用异常传播析构函数。

With the exception propagation destructors are called for all successfully constructed sub-objects, including base class sub-objects (if any).

然而,这不是完全构造的对象自己的析构函数不被调用。函数try块理想上不是一个用于做那些析构函数的设备。非完全创建的对象自己的析构函数没有任何关系,因为它的任务是清理由构造函数体和/或后来的成员函数调用引入的状态变化,并且使用通用的零规则设计,没有

However, this not completely constructed object's own destructor is not called. The function try block is ideally not a device for doing things that would go in that destructor. The not-completely-created object's own destructor has nothing to do, for its task is to clean up state changes introduced by the constructor body and/or later member function calls, and with a common "rule of zero" design there's no such as yet.

这篇关于为什么我们需要一个函数try块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆