简体   繁体   中英

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. But the outer catch P.who() gives the parent who() . And when I change the outer catch to Child type(not mentioned in the program) it terminates the process. Where is my understanding wrong?

What Scott Meyers says(with my edits)

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. 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 . It only throws a 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; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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