terminate_handler.cpp 1001 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <cstdlib>
  2. #include <exception>
  3. #include <util/stream/output.h>
  4. #include <util/system/backtrace.h>
  5. #include <util/generic/yexception.h>
  6. namespace {
  7. // Avoid infinite recursion if std::terminate is triggered anew by the
  8. // FancyTerminateHandler.
  9. thread_local int TerminateCount = 0;
  10. void FancyTerminateHandler() {
  11. switch (++TerminateCount) {
  12. case 1:
  13. break;
  14. case 2:
  15. Cerr << "FancyTerminateHandler called recursively" << Endl;
  16. [[fallthrough]];
  17. default:
  18. abort();
  19. break;
  20. }
  21. if (std::current_exception()) {
  22. Cerr << "Uncaught exception: " << CurrentExceptionMessage() << '\n';
  23. } else {
  24. Cerr << "Terminate for unknown reason (no current exception)\n";
  25. }
  26. PrintBackTrace();
  27. Cerr.Flush();
  28. abort();
  29. }
  30. [[maybe_unused]] auto _ = std::set_terminate(&FancyTerminateHandler);
  31. }