C++ - Arguments for Exceptions over Return Codes(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 -
- 构造函数不能给出返回码
- 将故障路径(这应该非常罕见)与更清晰的逻辑代码分离
- 在非异常情况下更快(无需检查 if/else 数十万次)
- 如果有人搞砸了返回代码设置(忘记返回 FAIL),可能需要很长时间才能找到.
- 错误中包含的消息中的更好信息.(有人向我指出,返回枚举可以对错误代码执行相同的操作)
- 来自 Jared Par 如果没有专门设计来处理它的代码,就不可能忽略
- Constructors can't give a return code
- Decouples the failure path (which should be very rare) from the logical code which is cleaner
- Faster in the non-exceptional case (no checking if/else hundreds of thousands of times)
- If someone screws up the return code settings (forgets to return FAIL) it can take a very long time to track down.
- 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)
- 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.
使用异常的参数
- 异常将错误处理代码与正常程序流分开,从而使代码更具可读性、健壮性和可扩展性.
- 抛出异常是从构造函数报告错误的唯一干净的方法.
- 与错误代码不同,异常很难被忽略.
- 异常很容易从深度嵌套的函数中传播.
- 异常可以并且通常是用户定义的类型,它们携带的信息远多于错误代码.
- 异常对象通过类型系统与处理程序匹配.
反对使用异常的论据
- 异常通过创建多个使代码难以阅读和检查的不可见退出点来破坏代码结构.
- 异常很容易导致资源泄漏,尤其是在没有内置垃圾收集器和 finally 块的语言中.
- 学习编写异常安全代码很难.
- 例外是昂贵的,并且违背了只为我们使用的东西付费的承诺.
- 很难在遗留代码中引入异常.
- 异常很容易被滥用来执行属于正常程序流程的任务.
这篇关于C++ - 返回码异常的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ - 返回码异常的参数
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
