Customizing termination behavior for uncaught exception In C++
Last Updated :
15 Apr, 2018
Improve
Whenever an exception arises in C++, it is handled as per the behavior defined using the try-catch block. However, there is often the case when an exception is thrown but isn't caught because the exception handling subsystem fails to find a matching catch block for that particular exception. In that case, the following set of actions takes place:
CPP
Output:
- The exception handling subsystem calls the function: unexpected(). This function, provided by the default C++ library, defines the behavior when an uncaught exception arises. By default, unexpected calls terminate().
- The terminate function defines the actions that are to be performed during process termination. This, by default, calls abort().
- The process is aborted.
// CPP program to set a new termination handler
// for uncaught exceptions.
#include <exception>
#include <iostream>
using namespace std;
// definition of custom termination function
void myhandler()
{
cout << "Inside new terminate handler\n";
abort();
}
int main()
{
// set new terminate handler
set_terminate(myhandler);
try {
cout << "Inside try block\n";
throw 100;
}
catch (char a) // won't catch an int exception
{
cout << "Inside catch block\n";
}
return 0;
}
Inside try block Inside new terminate handlerRuntime Error:
Abort signal from abort(3) (SIGABRT)It is to be duly noted that the only thing that your custom terminate handler must do is stop the program execution. It must not return to the program or resume it in any way.
Article Tags :