ktx
ktx

Reputation: 168

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

Upvotes: 8

Views: 236

Answers (1)

GManNickG
GManNickG

Reputation: 503785

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.

Upvotes: 12

Related Questions