Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crashing after catching exception

Tags:

c++

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;
}
like image 457
ktx Avatar asked Jul 18 '11 08:07

ktx


People also ask

What happens after exception is caught?

If exception occurs in try block then the rest of the statements inside try block are ignored and the corresponding catch block executes. After catch block, the finally block executes and then the rest of the program.

Does Try-Catch prevent crash?

And yes, it prevents crashes; but leads to all kind of "undefined" behavior. You know, when you just catch an exception instead of properly dealing with it; you open a can of worms; because you might run into myriads of follow-on errors that you later don't understand.

Does Try-Catch affect performance?

In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.

How do you handle catching exception?

The first catch block that handles the exception class or one of its superclasses will be executed. So, make sure to catch the most specific class first. If an exception occurs in the try block, the exception is thrown to the first catch block. If not, the Java exception passes down to the second catch statement.


1 Answers

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.

like image 178
GManNickG Avatar answered Nov 07 '22 04:11

GManNickG