关于set_terminate使用的问题

Vin*_*jan 2 exception terminate throw terminate-handler c++11

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

  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;

Run Code Online (Sandbox Code Playgroud)

Mik*_*han 5

如果您可以接受1隐含的可移植性限制,那么您可能可以接受下面的终止处理程序:<cxxabi.h>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;
}
Run Code Online (Sandbox Code Playgroud)

这将始终报告未捕获异常的类型,如果该类型派生自 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)
Run Code Online (Sandbox Code Playgroud)

请注意,您可能会避免调用set_terminate(backstop)- 可以想象,这可能会在大型复杂程序中的其他地方被取消 - 并确保任何逃逸主体的异常都main被捕获在函数 try-block中,即替换main为:

int main(int argc, char *argv[]) try
{
    if (argc > 1) {
        throw argv[1];
    } else {
        throw std::runtime_error("I am too tired to carry on");
    }
    return 0;
}
catch(...) {
    backstop();
}
Run Code Online (Sandbox Code Playgroud)

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


[1] 你至少会拥有 g++、clang++、icc;你不会有 MS C++