gpt4 book ai didi

c++ - 在 C++ 中引发异常和处理某些异常类型的正确方法是什么

转载 作者:太空宇宙 更新时间:2023-11-04 15:58:45 24 4
gpt4 key购买 nike

理论上知道如何创建和处理异常。但是在一个大项目中,一个函数可能会抛出很多不同的异常。

我如何设法解析我能收到的所有异常?

例如:

我目前正在实现一个数据库客户端。如果查询要求坏表或坏列,我会在低级驱动程序中抛出异常,如下所示:

throw MySQLException("message");

这将导致在客户端的顶层抛出一个 std::runtime_error 异常。所以我添加了以下代码来捕获异常:

try {
execute(query);
}
catch(std::exception &e) {
// How do I parse exception content?
}

但有没有比从 e.what() 中提取信息更好的方法来弄清楚它是哪种异常?目的是让每一种异常都对应一个错误码(不修改异常信息)。

我们将提供指向教程的链接。

最佳答案

您可以有多个 catch 语句,如下所示:

try {
execute(query);
}
catch (const my_custom_exception_type& e) {
}
catch (const std::runtime_error& e) {
}
catch (const std::exception& e) {
}
catch (...) {
// fallback - exception object is not any of the above types
}

控制将流入第一个参数类型与异常对象类型兼容的catch block 。如果没有匹配项并且没有 ... 包罗万象,则异常将从该 try/catch block 传播出去。可以找到对确切的 try/catch 行为的更精确的解释 here :

When an exception of type E is thrown by any statement in compound-statement, it is matched against the types of the formal parameters T of each catch-clause in handler-seq, in the order in which the catch clauses are listed. The exception is a match if any of the following is true:

  • E and T are the same type (ignoring top-level cv-qualifiers on T)
  • T is an lvalue-reference to (possibly cv-qualified) E
  • T is an unambiguous public base class of E
  • T is a reference to an unambiguous public base class of E
  • T is (possibly cv-qualified) U or const U& (since C++14), and U is a pointer or pointer to member (since C++17) type, and E is also a pointer or pointer to member (since C++17) type that is implicitly convertible to U by one or more of
    • a standard pointer conversion other than one to a private, protected, or ambiguous base class
    • a qualification conversion
    • a function pointer conversion (since C++17)
  • T is a pointer or a pointer to member or a reference to a const pointer (since C++14), while E is std::nullptr_t.

您还可以使用 RTTI确定 e 的类型,但尽可能避免这种情况。

关于c++ - 在 C++ 中引发异常和处理某些异常类型的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49634061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com