简体   繁体   English

为什么重新抛出的异常不能按预期工作?

[英]Why doesn't the rethrown exception work as expected?

My sample code: 我的示例代码:

#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
    }

}

I was going through Scott Meyers More Effective C++, Item 12. So when I rethrow it should propagate the Child exception. 我正在阅读Scott Meyers更有效的C ++,第12项。所以当我重新抛出它时,它应该传播Child异常。 But the outer catch P.who() gives the parent who() . 但外部catch P.who()给父母who() And when I change the outer catch to Child type(not mentioned in the program) it terminates the process. 当我将外部catch更改为Child类型(程序中未提及)时,它会终止进程。 Where is my understanding wrong? 我的理解在哪里错了?

What Scott Meyers says(with my edits) Scott Meyers说的话(我的编辑)

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.
}
.............
.............

If the exception originally thrown was of type Special Widget , the catch block would propagate a Special Widget exception , even though w 's static type is Widget. 如果最初抛出的异常是Special Widget类型, catch块会传播一个Special Widget异常,即使w的静态类型是Widget。 This is because no copy is make when the exception is rethrown. 这是因为重新抛出异常时不会复制。

 throw rw; //this throws an exception of type Widget! 

This does not throw a SpecialWidget . 这不会抛出SpecialWidget It only throws a Widget . 它只会抛出一个Widget

throw; never changes the type of the thrown object. 永远不会改变抛出对象的类型。 If the original object was a Child , it will still be a child after throw; 如果原始对象是一个Child ,它将在throw;后仍然是一个孩子throw; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM