如何捕获未知异常并打印出来

hel*_*rld 41 c++ exception

我有一些程序,每次我运行它,它抛出异常,我不知道如何检查究竟是什么抛出,所以我的问题是,是否有可能捕获异常并打印它(我发现行抛出异常)谢谢提前

R S*_*hko 53

如果它来源于std::exception你可以通过引用捕获:

try
{
    // code that could cause exception
}
catch (const std::exception &exc)
{
    // catch anything thrown within try block that derives from std::exception
    std::cerr << exc.what();
}
Run Code Online (Sandbox Code Playgroud)

但是如果异常是一些不是派生的类std::exception,你必须提前知道它的类型(即你应该抓住std::string或者some_library_exception_base).

你可以抓住所有:

try
{
}
catch (...)
{
}
Run Code Online (Sandbox Code Playgroud)

但是你不能对例外做任何事情.

  • 如果异常不是从std :: exception派生的,我应该如何解决我的问题? (3认同)

Daw*_*ozd 19

在C++ 11中,您有:std :: current_exception

来自网站的示例代码:

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>

void handle_eptr(std::exception_ptr eptr) // passing by value is ok
{
    try {
        if (eptr) {
            std::rethrow_exception(eptr);
        }
    } catch(const std::exception& e) {
        std::cout << "Caught exception \"" << e.what() << "\"\n";
    }
}

int main()
{
    std::exception_ptr eptr;
    try {
        std::string().at(1); // this generates an std::out_of_range
    } catch(...) {
        eptr = std::current_exception(); // capture
    }
    handle_eptr(eptr);
} // destructor for std::out_of_range called here, when the eptr is destructed
Run Code Online (Sandbox Code Playgroud)

  • 这没有帮助,它仍然只处理 std::exception。如果抛出类似 char* 的东西,这将无济于事。 (4认同)

Grz*_*zak 6

如果您使用 gcc 或 CLANG 的 ABI,您可以知道未知的异常类型。但这是非标准解决方案。

请参阅此处 /sf/answers/1749814601/

更新:

解决方案的要点是(不要使用这个,输出被破坏)

catch(...)
{
   cout << __cxxabiv1::__cxa_current_exception_type()->name();
}
Run Code Online (Sandbox Code Playgroud)

例如,如果您throw "foo";这样做,它将返回损坏的名称"PKc",如果您按照链接进行魔法解除损坏,则变为"char const*"