cpp异常获取throw调用者的详细信息

时间:2018-05-25 10:42:52

标签: c++ exception

我有一些自定义异常,如下面的

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} myex;

void testException(){
 throw myex;
}

void doSomething2(){
   testException();
}
void doSomething1(){
   doSomething2();
}


int main () {
  try
  {
    doSomething1();
  }
  catch (exception& e)
  {
    cout << e.what() << '\n';
  }
  return 0;
}

所以在main函数中我无法知道throw的调用者(哪个函数抛出异常),如何获取该细节?

2 个答案:

答案 0 :(得分:1)

在我所知道的C++中,没有简单的可移植方法可以做到这一点。有一些相当复杂的方法可以使用特定于操作系统的调用来获得完整的堆栈跟踪。

我用来获取异常源的最简单方法是使用MACROS。

不建议在可以避免的地方使用宏,但这是他们证明有用的少数几个地方之一。

我倾向于使用比这更复杂的东西,但这是它的基础:

#ifndef NDBUG
#define throw_runtime_error(msg) \
    throw std::runtime_error(std::string(msg) \
        + " line: " + std::to_string(__LINE__) \
        + " file: " + std::string(__FILE__))
#else
#define throw_runtime_error(msg) throw std::runtime_error(msg)
#endif

void doSomething2(){
    throw_runtime_error("My runtime error.");
}
void doSomething1(){
   doSomething2();
}

int main()
{
    try
    {
        doSomething1();
    }
    catch(std::exception const& e)
    {
        std::cerr << e.what() << '\n';
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

您没有获得完整的跟踪,但您确实可以看到引发异常的位置。 MACRO仅在未设置NDBUG时包含调试信息,因为 release 版本应设置该宏以禁用调试信息。

答案 1 :(得分:1)

这应该会有所帮助:

How to automatically generate a stacktrace when my gcc C++ program crashes

你可以找到打印调用堆栈的方法并在异常处理程序中打印它。

相关问题