函数try块,但不在构造函数中 [英] Function try blocks, but not in constructors

查看:138
本文介绍了函数try块,但不在构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个快速问题。

之间有什么区别

  void f(Foo x)try 
{
...
}
catch(exception& e)
{
...
}

  void f(Foo x)
{
try {...}
catch(exception& e)
{
...
}
}
pre>



如果没有,为什么是函数try块(构造函数的初始化列表放在一边) ?如果 Foo 的复制构造函数在 x 被传递给时抛出异常, / code>?

解决方案

函数try块只在构造函数中需要。在所有其他情况下,通过在正常try / catch块中包含函数的整个主体,可以实现完全相同的效果。



如果复制构造函数用于初始化参数会在之前发生异常。它不能被函数try块或异常处理函数捕获,因为函数不会被调用。


just a quick question. Is there any difference between

void f(Foo x) try
{
   ...
}
catch(exception& e)
{
   ...
}

and

void f(Foo x)
{
    try { ... }
    catch (exception& e)
    {
        ...
    }
}

?

If no, why are function try blocks for (the case of initialization lists for constructors being put aside) ? What happens if the copy constructor of Foo throws an exception when x is passed to f ?

解决方案

Function try blocks are only ever needed in constructors. In all other cases exactly the same effect can be achieved by enclosing the entire body of the function in a normal try/catch block.

If the copy constructor used to initialize a parameter throws an exception this happens before the function call. It cannot be caught by a function try block or exceptional handler in the function as the function doesn't get called.

这篇关于函数try块,但不在构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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