簡體   English   中英

為什么重新拋出的異常不能按預期工作?

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

我的示例代碼:

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

}

我正在閱讀Scott Meyers更有效的C ++,第12項。所以當我重新拋出它時,它應該傳播Child異常。 但外部catch P.who()給父母who() 當我將外部catch更改為Child類型(程序中未提及)時,它會終止進程。 我的理解在哪里錯了?

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

如果最初拋出的異常是Special Widget類型, catch塊會傳播一個Special Widget異常,即使w的靜態類型是Widget。 這是因為重新拋出異常時不會復制。

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

這不會拋出SpecialWidget 它只會拋出一個Widget

throw; 永遠不會改變拋出對象的類型。 如果原始對象是一個Child ,它將在throw;后仍然是一個孩子throw;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM