有关set_terminate使用的问题

问题描述 投票:1回答:1

我有以下示例。 (我的实际项目是一个多线程的项目,我为所有项目设置了终止处理程序。)我在这里有几个问题。

  1. 我的终止处理程序没有任何幻想。它仅表示发生了错误并退出。我读到,添加处理程序是一种很好的做法。为什么会这样,在这种情况下我真的需要吗?

  2. 如果我没有处理程序,则会得到抛出的异常类型。 terminate called after throwing an instance of 'char const*'但是当我使用处理程序时,我无法获取它。即使我使用current_exception,也无法获取异常类型。 (这里显然是char *,但是在我的情况下可能是任何东西,所以我无法正确捕获。即使我使用catch {...},消息和类型也会丢失)。反正有没有得到消息。如果没有消息,至少可以获取抛出异常的类型吗?

// set_terminate example
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;

void myterminate () {
  cerr << "terminate handler called\n";
  abort();  // forces abnormal termination
}

int main (void) {
  //set_terminate (myterminate);
  throw "TEST";  // unhandled exception: calls terminate handler
  return 0;

c++11 exception terminate throw terminate-handler
1个回答
0
投票

如果您可以忍受<cxxabi.h> 1暗示的可移植性限制,那么您可以使用下面的<cxxabi.h>终止处理程序:

main.cpp

backstop()

这将始终报告未捕获的异常的类型,如果该类型源自#include <iostream> #include <exception> #include <stdexcept> #include <cstdlib> #include <cxxabi.h> void backstop() { auto const ep = std::current_exception(); if (ep) { try { int status; auto const etype = abi::__cxa_demangle(abi::__cxa_current_exception_type()->name(), 0, 0, &status); std::cerr << "Terminating with uncaught exception of type `" << etype << "`"; std::rethrow_exception(ep); } catch(const std::exception& e) { std::cerr << " with `what()` = \"" << e.what() << "\""; } catch(...) {} std::cerr << std::endl; } std::abort(); } int main(int argc, char *argv[]) { std::set_terminate(backstop); if (argc > 1) { throw argv[1]; } else { throw std::runtime_error("I am too tired to carry on"); } return 0; } ,它还将报告该异常的std::exception。例如:

what()

[请注意,您可能避免调用$ g++ --version g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 ... $ g++ -Wall -Wextra -pedantic main.cpp; ./a.out Whoops! Terminating with uncaught exception of type `char*` Aborted (core dumped) $ clang++ --version clang version 10.0.0-4ubuntu1 ... $ clang++ -Wall -Wextra -pedantic main.cpp; ./a.out Terminating with uncaught exception of type `std::runtime_error` with `what()` = "I am too tired to carry on" Aborted (core dumped) -可能是在一个大型的复杂程序中反击其他地方-并确保任何set_terminate(backstop)主体的转义异常被main捕获,即将function try-block替换为:

main

此程序将像以前一样运行。


[1]您至少要有g ++,clang ++,icc;您将没有MS C ++

© www.soinside.com 2019 - 2024. All rights reserved.