E.15: Catch exceptions from a hierarchy by reference

E.15: 使用引用形式捕捉继承体系中的异常

 

Reason(原因)

To prevent slicing.

为了避免截断。

 

Example(示例)

void f()
{
try {
// ...
}
catch (exception e) { // don't: may slice
// ...
}
}

Instead, use a reference:

使用引用代替:

catch (exception& e) { /* ... */ }

or - typically better still - a const reference:

或者-一般会更好-使用常量引用:

catch (const exception& e) { /* ... */ }

Most handlers do not modify their exception and in general we recommend use of const.

大多数处理程序不会改变异常的内容,因此通常我们推荐使用常量形式。

 

Note(注意)

To rethrow a caught exception use throw; not throw e;. Using throw e; would throw a new copy of e (sliced to the static type std::exception) instead of rethrowing the original exception of type std::runtime_error. (But keep Don't try to catch every exception in every function and Minimize the use of explicit try/catch in mind.)

使用throw;重新抛出已经捕获的异常;不是throw e;。使用throw e;会抛出一个e的新拷贝(静态类型std::exception的截断结果)而不是重新抛出类型为std::runtime_error的原始异常。(但是还是要坚持:不要试图在每个函数中捕捉所有的异常并且别忘了尽量少用显式try/catch。)

 

Enforcement(实施建议)

Flag by-value exceptions if their types are part of a hierarchy (could require whole-program analysis to be perfect).

如果异常类型是类层次关系中一部分,标记传值用法(这会要求整个程序的解析更完美)。

 

原文链接

​https:///isocpp/CppCoreGuidelines/blob/master/#e15-catch-exceptions-from-a-hierarchy-by-reference​

 

新书介绍

以下是本人3月份出版的新书,拜托多多关注!

 

C++核心准则E.15: 使用引用形式捕捉继承体系中的异常_异常

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 


 

觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

 

C++核心准则E.15: 使用引用形式捕捉继承体系中的异常_C++_02