throw 和 throw with arg of catch Exception 有什么区别?
想象两段相似的代码:
try {
[...]
} catch (myErr &err) {
err.append("More info added to error...");
throw err;
}
它们
try {
[...]
} catch (myErr &err) {
err.append("More info added to error...");
throw;
}
实际上是相同的还是有一些微妙的不同?例如,第一个是否会导致运行复制构造函数,而第二个可能会重用同一对象来重新抛出它?
Imagine two similar pieces of code:
try {
[...]
} catch (myErr &err) {
err.append("More info added to error...");
throw err;
}
and
try {
[...]
} catch (myErr &err) {
err.append("More info added to error...");
throw;
}
Are these effectively the same or do they differ in some subtle way? For example, does the first one cause a copy constructor to be run whereas perhaps the second reuses the same object to rethrow it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您安排异常层次结构的方式,通过在 throw 语句中命名异常变量来重新引发异常可能会分割原始异常对象。
无参数的 throw 表达式将抛出当前异常对象,并保留其动态类型,而带参数的 throw 表达式将根据
throw< 的参数的 static 类型抛出新的异常/代码>。
例如,
如上面所写,程序将输出:
如果将
throw b
替换为throw
,则外层 catch 也会捕获最初抛出的Derived 异常。如果内部类通过值而不是通过引用捕获
Base
异常,这仍然成立 - 尽管这自然意味着原始异常对象无法修改,因此对b
的任何更改> 不会反映在外部块捕获的Derived
异常中。Depending on how you have arranged your exception hierarchy, re-throwing an exception by naming the exception variable in the throw statement may slice the original exception object.
A no-argument throw expression will throw the current exception object preserving its dynamic type, whereas a throw expression with an argument will throw a new exception based on the static type of the argument to
throw
.E.g.
As written above, the program will output:
If the
throw b
is replace with athrow
, then the outer catch will also catch the originally thrownDerived
exception. This still holds if the inner class catches theBase
exception by value instead of by reference - although naturally this would mean that the original exception object cannot be modified, so any changes tob
would not be reflected in theDerived
exception caught by the outer block.在第二种情况下,根据 C++ 标准 15.1/6,不使用复制构造函数:
在第一种情况下,将根据 15.1/3 抛出新的异常:
在这两种情况下,抛出阶段都需要复制构造函数(15.1/5):
In the second case according to C++ Standard 15.1/6 copy constructor is not used:
In the first case new exception will be thrown according to 15.1/3:
In both cases copy constructor is required at throw stage (15.1/5):