如何获得catch-all异常的消息

5Yr*_*DBA 31 c++ exception-handling visual-c++

如果我想在捕获全部异常时将有用信息写入文件,该怎么做?

try
{
   //call dll from other company
}
catch(...)
{
   //how to write info to file here???????
}
Run Code Online (Sandbox Code Playgroud)

utn*_*tim 57

您无法从... catch块中获取任何信息.这就是代码通常处理这样的异常的原因:

try
{
    // do stuff that may throw or fail
}
catch(const std::runtime_error& re)
{
    // speciffic handling for runtime_error
    std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const std::exception& ex)
{
    // speciffic handling for all exceptions extending std::exception, except
    // std::runtime_error which is handled explicitly
    std::cerr << "Error occurred: " << ex.what() << std::endl;
}
catch(...)
{
    // catch any other errors (that we have no information about)
    std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)


Per*_*tte 10

函数std :: current_exception()可以访问捕获的异常,该函数在<exception>中定义.这是在C++ 11中引入的.

std::exception_ptr current_exception();
Run Code Online (Sandbox Code Playgroud)

但是,std :: exception_ptr是一个实现定义的类型,因此无论如何都无法获取详细信息. typeid(current_exception()).name()告诉你exception_ptr,而不是包含的异常.所以你可以用它做的唯一事情是std :: rethrow_exception().(这个函数似乎可以在线程之间标准化catch-pass-and-rethrow.)


Fre*_*son 6

无法在catch-all处理程序中了解有关特定异常的任何信息.如果可以捕获基类异常(例如std :: exception),那么最好.