C++ - 返回码异常的参数

2021-12-17 00:00:00 exception c++

我正在讨论在新的 C++ 项目中采用哪种方式.出于以下原因,我更喜欢异常而不是返回代码(仅适用于例外情况) -

I'm having a discussion about which way to go in a new C++ project. I favor exceptions over return codes (for exceptional cases only) for the following reasons -

  1. 构造函数不能给出返回码
  2. 将故障路径(这应该非常罕见)与更清晰的逻辑代码分离
  3. 在非异常情况下更快(无需检查 if/else 数十万次)
  4. 如果有人搞砸了返回代码设置(忘记返回 FAIL),可能需要很长时间才能找到.
  5. 错误中包含的消息中的更好信息.(有人向我指出,返回枚举可以对错误代码执行相同的操作)
  6. 来自 Jared Par 如果没有专门设计来处理它的代码,就不可能忽略
  1. Constructors can't give a return code
  2. Decouples the failure path (which should be very rare) from the logical code which is cleaner
  3. Faster in the non-exceptional case (no checking if/else hundreds of thousands of times)
  4. If someone screws up the return code settings (forgets to return FAIL) it can take a very long time to track down.
  5. Better information from the message contained in the error. (It was pointed out to me that a return enum could do the same for error codes)
  6. From Jared Par Impossible to ignore without code to specifically designed to handle it

这些是我从思考和谷歌搜索中得出的观点.我必须承认,过去几年在 C# 中工作过的人很容易出现异常.请发布在返回代码上使用异常的进一步原因.对于那些喜欢返回代码的人,我也愿意听听你的推理.谢谢

These are the points I've come up with from thinking about it and from google searches. I must admit to being predisposed to exceptions having worked in C# for the past couple of years. Please post further reasons for using exceptions over return codes. For those who prefer return codes, I would also be willing to listen to your reasoning. Thanks

推荐答案

我认为这篇 文章 总结一下.

I think this article sums it up.

使用异常的参数

  1. 异常将错误处理代码与正常程序流分开,从而使代码更具可读性、健壮性和可扩展性.
  2. 抛出异常是从构造函数报告错误的唯一干净的方法.
  3. 与错误代码不同,异常很难被忽略.
  4. 异常很容易从深度嵌套的函数中传播.
  5. 异常可以并且通常是用户定义的类型,它们携带的信息远多于错误代码.
  6. 异常对象通过类型系统与处理程序匹配.

反对使用异常的论据

  1. 异常通过创建多个使代码难以阅读和检查的不可见退出点来破坏代码结构.
  2. 异常很容易导致资源泄漏,尤其是在没有内置垃圾收集器和 finally 块的语言中.
  3. 学习编写异常安全代码很难.
  4. 例外是昂贵的,并且违背了只为我们使用的东西付费的承诺.
  5. 很难在遗留代码中引入异常.
  6. 异常很容易被滥用来执行属于正常程序流程的任务.

相关文章