2011-07-18 115 views
8

爲什麼在捕獲std :: bad_exception之後崩潰? (我正在使用VC7)捕獲異常後崩潰

#include "stdafx.h" 
#include <exception> 

int validateInt (int x) throw (int,std::bad_exception) { 
    if (0 == x) { 
     throw std::bad_exception("x"); 
    } 
    return x; 
} 

class C { 
    int i;  
public: 
    C(int); 
}; 

C::C(int ii) 
try : i(validateInt(ii)) { 
    std::cout << "I'm in constructor function body\n"; 
} catch (std::exception& e) { 
    std::cout << "I caught an exception...\n"; 
} 

int _tmain(int argc, _TCHAR* argv[]) { 
    C a(0); 
    return 0; 
} 
+1

這是如何編譯...? –

+3

你是什麼意思?圍繞構建初始化列表的try-catch塊是合法的C++。 – anonymvs

+2

哇。我從未見過它被使用過,也從未聽說過它。 –

回答

12

因爲無法阻止異常從構造函數初始化列表中刪除。在你捕捉它之後,它會自動重新運行。 (然後崩潰,因爲你有一個不受歡迎的例外。)

這是一件好事:如果你的成員不能正確初始化,你的類不能正常存在。

+0

我試過圍繞「C a(0);」與一個try-catch塊,並沒有問題。但我認爲這並不好。 – anonymvs