Search code examples
c++exceptionterminate

Can anyone tell me when called terminate(), and when unexpected()?


What happens when ended function f() and g() ?

#include<iostream>
using namespace std;

class A
{
     ~A(){}

}
void f()
{
    cout << "terminate" << endl;

}
void g()
{
    cout << "unexpected" << endl;
}



int main()
{
    set_terminate(f);
    set_unexpected(g);
    throw 5;
    cout << "end" << endl;
    return 0;
}

Why is called abort() function? And when is called destruktor? I can't find logic :((((((((


Solution

  • The relevant rules are clearly defined in the standard, There are a number of rules but simply said and put the ones that apply to your example are:

    • throw without a catch results in call to terminate or the function set for it.
    • When a exception thrown does not match the exception specification results in a call to unexpected or the function set for it.

    15.1 Throwing an exception
    Para 8:

    If no exception is presently being handled, executing a throw-expression with no operand calls terminate() (15.5.1).

    15.4 Exception specifications
    Para 8:

    Whenever an exception is thrown and the search for a handler (15.3) encounters the outermost block of a function with an exception-specification, the function unexpected() is called (15.5.2) if the exceptionspecification does not allow the exception


    Why does your program call abort?

    Your program has an undefined behavior. It is compliant with the fact that you set the terminate_handler appropriately and as you notice the program does result in call to f() but the required behavior for a terminate_handler function is:

    C++03 Standard 18.6.3.1.2:

    A terminate_handler shall terminate execution of the program without returning to the caller.

    Your terminate_handler function f does not satisfy this condition and hence results in Undefined behavior and technically it is possible that you can get any behavior, your implementation chooses to call abort in this situation. Nothing stops it from doing so.