Logging with a custom terminate handler

How can I use a custom terminate handler to log information about an unhandled exception?

You can use a custom terminate handler to log information about an unhandled exception before terminating the program. Here's an example of how you can set up a custom terminate handler for logging:

#include <exception>
#include <iostream>

void customTerminateHandler() {
  try {
    std::exception_ptr exPtr =
      std::current_exception();
    if (exPtr) {
      std::rethrow_exception(exPtr);
    }
  } catch (const std::exception& ex) {
    std::cout << "Unhandled exception: "
      << ex.what() << '\n';  
  } catch (...) {
    std::cout << "Unhandled unknown exception\n";
  }
  std::abort();
}

int main() {
  std::set_terminate(customTerminateHandler);

  try {
    throw std::runtime_error(
      "Something went wrong");
  } catch (const std::logic_error& ex) {
    // Catch and handle logic_error exceptions
  }
}
Unhandled exception: Something went wrong

In this example:

  1. We define a custom terminate handler function customTerminateHandler.
  2. Inside the handler, we retrieve the currently thrown exception using std::current_exception().
  3. If an exception pointer is obtained, we rethrow the exception to catch and log its details.
  4. We catch specific exception types (e.g., std::exception) and log their error messages using ex.what().
  5. For unknown exceptions, we log a generic message.
  6. Finally, we call std::abort() to terminate the program.

In the main() function:

  1. We set the custom terminate handler using std::set_terminate().
  2. We intentionally throw an exception that is not caught by the provided catch block.

When the unhandled exception is thrown, the custom terminate handler is invoked, logging the exception details before terminating the program.

Using std::terminate() and the noexcept Specifier

This lesson explores the std::terminate() function and noexcept specifier, with particular focus on their interactions with move semantics.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Difference between std::terminate and std::abort
What is the difference between std::terminate() and std::abort() in C++?
Handling exceptions in noexcept functions
How can I handle exceptions within a noexcept function without terminating the program?
Implementing a noexcept move assignment operator
How can I implement a noexcept move assignment operator for a custom type?
Using noexcept with move-only types
Why is noexcept important when working with move-only types?
noexcept and exception guarantees
How does the noexcept specifier relate to exception safety guarantees in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant