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:
- 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.
The terminate() and unexpected() simply call other functions to actually handle an error. As explained above, terminate calls abort(), and unexpected() calls terminate(). Thus, both functions halt the program execution when an exception handling error occurs. However, you can change the way termination occurs.
To change the terminate handler, the function used is set_terminate(terminate_handler newhandler), which is defined in the header <exception>.
The following program demonstrates how to set a custom termination handler:
Inside try block Inside new terminate handler
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.
- Undefined Behavior in C and C++
- Exception Handling in C++
- Handling the Divide by Zero Exception in C++
- Comparison of Exception Handling in C++ and Java
- Exception handling and object destruction | Set 1
- Vector of Vectors in C++ STL with Examples
- Array of Vectors in C++ STL
- Difference between Virtual function and Pure virtual function in C++
- cin get() in C++ with Examples
- Difference between Increment and Decrement Operators
- Map of Vectors in C++ STL with Examples
- Problem in comparing Floating point numbers and how to compare them correctly?
- exit(0) vs exit(1) in C/C++ with Examples
- C++ program to print all Even and Odd numbers from 1 to N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.