2012-04-19 77 views

回答

2

在C++中,在異常聲明說明符中,如果我聲明一個基類然後拋出一個派生類,那是一個意外的異常嗎?

不可以。

參考: C++ 03 15.4異常規範

帕拉6:

例外規格可以包括相同類型的多於一次,並且可以包括作爲相關的類通過繼承,即使這樣做是多餘的。異常規範也可以包含類std :: bad_exception(18.6.2.1)。

有一個在
第8段相關的例子:

[Example: 
class X { }; 
class Y { }; 
class Z: public X { }; 
class W { }; 
void f() throw (X, Y) 
{ 
    int n = 0; 
    if (n) throw X(); // OK 
    if (n) throw Z(); // also OK <------- Example of the exact scenario you posted 
    throw W(); // will call unexpected() 
} 
—end example] 

注意異常規範被視爲失敗和大多數編譯器不正確地實現他們的實驗。所以請避免(而不要)使用它們。

0

我知道這是可怕的非答案,但請不要使用異常規格:

http://www.gotw.ca/publications/mill22.htm

引述相關部分:

道德#1:不要寫一個異常規範。

道德#2:除了可能是一個空的,但如果我是你,我甚至會避免。

在C++ 11中對#2的警告是「noexcept」。

相關問題