Search code examples
c++exceptionmingwclion

Why doesn't the exception quit the program?


This is my custom exception:

class MyException {
public:
    MyException()
            :message("..."){}
    const char *what() const {return message;}
private:
    const char * message;
};

This is the class:

Class MyClass {
    void function() {
        // [...]
        if (condition) throw MyException();
        // [...]
    }
};

main.cpp:

MyClass a;
try {
    a.function();
}
catch (MyException & ex) {
    cerr << ex.what() << endl;
}

I thought that the program was going to quit if condition == true, but instead it proceeds... Why? (The message is regularly displayed)

P.S.

The same if I do something like:

function2();

int main {
    function2();
}

function2() {
    try {
        // something that may create an exception
    }
    catch (MyException & ex) {
        cerr << ex.what() << endl;
    }
}

Solution

  • You caught the exception that is why the program didn't crash. The point of exception handling is to catch exceptions and handle them gracefully.