【问题标题】:how to get message of catch-all exception [duplicate]如何获取全部异常的消息[重复]
【发布时间】:2011-03-09 03:46:16
【问题描述】:

如果我想在捕获到包罗万象的异常时将有用的信息写入文件,该怎么做?

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

【问题讨论】:

  • 您希望从异常中得到什么信息?如果抛出的对象是int 怎么办?当您catch(...) 时,您不知道捕获的异常会 一条消息。
  • 这个问题给了我一个奇怪的想法(它不会起作用,但如果它起作用会很有趣):template catch(const T& ex) {...}我认为它不可能起作用,因为异常更像是一种运行时机制......或者可以吗?抛出异常和分支到正确的 catch 块所涉及的堆栈展开机制对我来说似乎很神奇。也许要分支到的正确 catch 块仍然在编译时确定,这可以解释为什么跨模块边界抛出是如此不安全的原因之一。

标签: c++ visual-c++ exception-handling


【解决方案1】:

您无法从 ... 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;
}

【讨论】:

  • 是否有可能以某种方式包装这些 catch 子句,这样它们就不必在任何使用 try 子句的地方重复?
【解决方案2】:

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

std::exception_ptr current_exception();

但是,std::exception_ptr 是实现定义的类型,所以无论如何您都无法了解详细信息。 typeid(current_exception()).name() 告诉你 exception_ptr,而不是包含的异常。所以你唯一能用它做的就是std::rethrow_exception()。 (这个函数似乎是为了标准化跨线程的 catch-pass-and-rethrow。)

【讨论】:

    【解决方案3】:

    您无法获得任何详细信息。 catch(...) 的全部意义在于拥有这样的“我不知道会发生什么,所以抓住任何抛出的东西”。对于已知的异常类型,您通常将 catch(...) 放在 catch'es 之后。

    【讨论】:

      【解决方案4】:

      我认为他想让它记录发生的错误,但并不特别需要确切的错误(在这种情况下他会编写自己的错误文本)。

      上面发布的 DumbCoder 链接在教程中可以帮助您获得您想要实现的目标。

      【讨论】:

        【解决方案5】:

        没有办法知道关于包罗万象的处理程序中的特定异常的任何信息。如果可能的话,最好能捕获基类异常,例如 std::exception。

        【讨论】:

          猜你喜欢
          • 2023-03-08
          • 1970-01-01
          • 2017-02-04
          • 2014-06-14
          • 1970-01-01
          • 2011-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多