简体   繁体   中英

Crashing after catching exception

Why does this crash after catching std::bad_exception? (I'm using 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;
}

Because you cannot stop exceptions from leaving the constructor initialization list. After you catch it, it's rethrown automatically. (It then crashes because you have an unhanded exception.)

This is a good thing: if your members cannot be properly initialized, your class cannot properly exist.

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