C++核心准则E.31:正确排列catch子句

时间:2022-07-23
本文章向大家介绍C++核心准则E.31:正确排列catch子句,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

E.31: Properly order your catch-clauses

E.31:正确排列catch子句

Reason(原因)

catch-clauses are evaluated in the order they appear and one clause can hide another.

catch子句按照它们表示的次序行,一个子句出发之后,其他子句不再执行。

Example(示例)

void f()
{
    // ...
    try {
            // ...
    }
    catch (Base& b) { /* ... */ }
    catch (Derived& d) { /* ... */ }
    catch (...) { /* ... */ }
    catch (std::exception& e) { /* ... */ }
}

If Derivedis derived from Base the Derived-handler will never be invoked. The "catch everything" handler ensured that the std::exception-handler will never be invoked.

如果Deriveds是Base的派生类,捕捉派生类的处理永远不会执行。捕捉所有异常的处理会导致捕捉std::exception的处理程序永远不会执行。

Enforcement(实施建议)

Flag all "hiding handlers".

标记所有被隐藏的异常处理程序。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e31-properly-order-your-catch-clauses