What happens if a thrown exception is not handled in C++?

In the event that an exception is thrown but not handled, this means that a matching handler does not exist for the exception that was thrown. This also means that an ellipsis catch handler was not found either.

So, what will happen in this scenario? Well, C++ has a predefined function called terminate which will be called when there is no matching handler for the exception. The terminate function will then call another function named abort. The abort function will then stop program execution.

However, it’s also worth pointing out that the terminate function can be redefined to call some other function – that’s not abort – before exiting the application. To do this you can just use the set_terminate function, and pass in the name of the function that you want to be called instead as the one and only argument to the set_terminate function. Here’s an example of how the set_terminate function would be used in C++:

#include   //this is for function prototypes

void end_func() 
{  // ...
}

int main()
{
  try
  {
     // ....
     set_terminate( end_func );

    // note that there is no matching catch
    // block to handle this exception being thrown:
    //...
    throw "No more memory";

  }
}

catch ( int )   
{
cout << "Exception for integer thrown!";
}

return 0;

}

As you can see in the code above, we used the set_terminate function and passed another function called end_func into it as an argument. This means that the program, or current thread, should now be terminated by a call to the end_func function. The best situation would be if end_func would call "exit".

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

  • James

    There’s an extra closing curly brace ( ‘}’ ) after the try{} block.

    I assume the catch (int) before the return 0; is also unintentional?