函数try块,但不在构造函数中 [英] Function try blocks, but not in constructors
问题描述
只是一个快速问题。
之间有什么区别 void f(Foo x)try
{
...
}
catch(exception& e)
{
...
}
和
void f(Foo x)
pre>
{
try {...}
catch(exception& e)
{
...
}
}
?
如果没有,为什么是函数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 whenx
is passed tof
?解决方案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屋!