In C++, exceptions are normally handled using try and catch blocks. However, if an exception is thrown and no matching catch block is found, the program invokes the termination mechanism, which results in abnormal program termination.
- Uncaught exceptions cause the program to terminate immediately.
- Allows programmers to customize the behavior that occurs before program termination.
Example: Setting a Custom Termination Handler
#include <exception>
#include <iostream>
using namespace std;
// Custom termination handler
void myHandler()
{
cout << "Inside custom terminate handler\n";
// Terminate the program
abort();
}
int main()
{
// Install custom terminate handler
set_terminate(myHandler);
try {
cout << "Inside try block\n";
throw 100;
}
// Does not match int exception
catch (char c) {
cout << "Inside catch block\n";
}
return 0;
}
Output
Inside try block
Inside custom terminate handler
Runtime Error:
Abort signal from abort() (SIGABRT)Explanation: The exception thrown inside the try block is not caught by the catch(char) block because the exception type is int. As a result, std::terminate() is invoked, which calls the custom terminate handler installed using set_terminate().
Default Behavior for Uncaught Exceptions
When an exception is thrown and no matching exception handler exists, the following sequence of events occurs:
- The exception handling subsystem fails to find a matching catch block.
- The function std::terminate() is invoked.
- By default, std::terminate() calls std::abort().
- The program terminates immediately.
Note: Earlier C++ standards also provided unexpected(), but it was deprecated in C++11 and removed in C++17. Modern C++ uses std::terminate() to handle uncaught exceptions.
Customizing the Termination Handler
C++ provides the std::set_terminate() function, defined in the <exception> header, which allows programmers to install a custom termination handler.
Syntax
std::terminate_handler
set_terminate(std::terminate_handler new_handler);
- Parameters: new_handler - Pointer to the custom termination function.
- Return Value: returns the previously installed termination handler.
Points to Remember About set_terminate()
This section should contain facts about the API and its behavior:
- set_terminate() allows customization of program termination behavior.
- The custom termination handler is invoked whenever std::terminate() executes.
- Only one terminate handler can be active at a time.
- A terminate handler must not return to the calling program.
Best Practices
This section should contain recommendations for writing good code:
- Use custom terminate handlers mainly for logging or debugging purposes.
- Keep the terminate handler short and simple.
- Avoid throwing exceptions from a terminate handler.
- Avoid performing complex operations or resource management inside a terminate handler.