C++ 为什么';rethrown异常是否按预期工作?
我的示例代码:C++ 为什么';rethrown异常是否按预期工作?,c++,exception,inheritance,C++,Exception,Inheritance,我的示例代码: #include<iostream> using namespace std; class Parent{ public: virtual void who() { cout<<"I am parent"<<endl; } }; class Child: public Parent { public:
#include<iostream>
using namespace std;
class Parent{
public:
virtual void who()
{
cout<<"I am parent"<<endl;
}
};
class Child: public Parent
{
public:
void who()
{
cout<<"I am child"<<endl;
}
};
int main()
{
try{
try{
Child C;
Parent &P=C;
throw P;
}
catch(Parent &P)
{
P.who();
throw;//here it just propagates the Child exception
}
}
catch(Parent &P)
{
P.who();//parent who is getting executed
}
}
如果最初抛出的异常类型为Special Widget
,则catch
块将传播Special Widget
异常,即使w
的静态类型为Widget。这是因为当异常被重试时,不会生成副本
这不会抛出特殊Widget
。它只抛出一个小部件
抛出代码>从不更改抛出对象的类型。如果原始对象是子对象
,则抛出后仍将是子对象
对于我来说,内部的catch已经打印出了我是家长
(使用VC、clang和GCC)。因此,在抛出之前或之后,异常绝不属于Child
类型代码>重新抛出是一种转移注意力的方法。因此,对象切片在这里发生了吗?“[except.throw]/3抛出异常副本会初始化(8.5,12.8)一个临时对象,称为异常对象。临时对象…用于初始化匹配处理程序(15.3)中声明的变量。”
不会抛出rw
引用的对象,而是从rw
初始化的临时对象副本。是的,这里有切片。
class Widget{...};
class Special Widget: public Widget { ... };
void passAndThrowWidget()
{
SpecialWidget localSpecialWidget;
...
Widget& rw = localSpecialWidget;
throw rw; //this throws an exception of type Widget!
}
................
................
catch(Widget &w) //catch Widget exceptions
{
...
throw; //rethrow the exception so it continues to propagate.
}
.............
.............
throw rw; //this throws an exception of type Widget!