Customizing termination behavior for uncaught exception In C++


In this tutorial, we will be discussing a program to customize behavior for an uncaught exceptions in C++.

Usually, the exception is handled by the try-catch block, but there are instances where there isn’t a matching catch block and the program just terminates. This terminate() function is modifiable as per user requirements.

Example

 Live Demo

#include <exception>
#include <iostream>
using namespace std;
//defining custom terminator
void myhandler(){
   cout << "Inside new terminate handler\n";
   abort();
}
int main(){
   set_terminate(myhandler);
   try {
      cout << "Inside try block\n";
      throw 100;
   }
   catch (char a){
      cout << "Inside catch block\n";
   }
   return 0;
}

Output

Inside try block
Inside new terminate handler

Updated on: 23-Mar-2020

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements