为什么要捕获异常作为对 const 的引用? [英] Why catch an exception as reference-to-const?

查看:25
本文介绍了为什么要捕获异常作为对 const 的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次听说并阅读过,最好将异常作为对常量的引用而不是作为引用来捕获.为什么是:

I've heard and read many times that it is better to catch an exception as reference-to-const rather than as reference. Why is:

try {
    // stuff
} catch (const std::exception& e) {
    // stuff
}

优于:

try {
    // stuff
} catch (std::exception& e) {
    // stuff
}

推荐答案

您需要:

  • 一个引用,以便您可以多态地访问异常
  • 用于提高性能的常量,并告诉编译器您不会修改对象

后者不如前者重要,但放弃 const 的唯一真正原因是表明您想要对异常进行更改(通常只有在您想要更改时才有用)将添加的上下文重新抛出到更高级别).

The latter is not as much important as the former, but the only real reason to drop const would be to signal that you want to do changes to the exception (usually useful only if you want to rethrow it with added context into a higher level).

这篇关于为什么要捕获异常作为对 const 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆