【问题标题】:How to know the exception type for std::exception如何知道 std::exception 的异常类型
【发布时间】:2019-12-12 21:09:24
【问题描述】:

我有一个如下所示的 try-catch 块

try
{
   // Do something here.
}
catch (const std::exception &e)
{
   // std exception. 
}
catch(...)
{
    // Unknown exception. We can't know the type.
}

我正在阅读来自http://www.cplusplus.com/reference/exception/exception/ 的一些文档,但对我来说,当代码进入 std::exception 部分时如何知道捕获的异常类型并不明显。

有没有办法获取错误类型的字符串? (我不想暴露错误信息,只是异常类型)

【问题讨论】:

  • 您只能指定您预期的异常类型。您无法获得异常的具体类型。您需要将此行为实现到您自己的异常类型中。
  • 我明白了.. 所以没有办法像在 C# 上使用 getType 函数那样做到这一点,对吧?
  • 与 C# 相比,C++ 的类型反射功能非常有限。最接近的可能是type_info,但您获得的名称取决于平台,除了打印或日志记录之外不是很有用。编辑:看起来@Brian 的回答涵盖了这一点。
  • 是的,这是为了记录目的,所以我认为这样可以解决问题。试图弄清楚这是如何工作的

标签: c++ exception


【解决方案1】:

有没有办法获取错误类型的字符串?

有点。如果您通过引用捕获(正如您在上面的代码中所做的那样),那么您可以将typeid 应用于异常以获取有关其动态类型的一些信息。这是因为std::exception 是一种多态类型。但是,不能保证 std::type_info::name() 是该类型的可读名称。

【讨论】:

  • 也许这要求太多了,但你能添加一个关于如何使用 std::type_info::name() 中的 typeid 的示例吗?
  • @user3587624: std::cout << typeid(e).name();
【解决方案2】:

您可以使用不同的catch 块捕获不同的异常:

try
{
   // Do something here.
}
catch (const std::runtime_error& e) 
{
   // Handle runtime error
}
catch (const std::out_of_range& e) 
{
   // Handle out of range
}
catch (const std::exception &e)
{
   // Handle all other exceptions 
}
catch(...)
{
    // Unknown exception. We can't know the type.
}

当然,为每种类型的异常单独捕获并不总是有意义的,因此您仍然需要一种方法来判断 catch(std::exception&) 块中的异常类型是什么,我建议您这样做到this answer

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多