C ++ - 返回代码异常的参数 [英] C++ - Arguments for Exceptions over Return Codes
问题描述
我正在讨论在新的C ++项目中采用哪种方式。我赞成例外而非返回代码(仅适用于特殊情况),原因如下 -
- 构造函数无法提供返回代码
- 从更清晰的逻辑代码中解耦故障路径(非常罕见)
- 在非特殊情况下更快
- 如果有人拧紧了返回代码设置(忘记返回FAIL),则可能需要很长时间才能跟踪。
- 错误中包含的邮件中的更好的信息。 (对我来说,返回枚举对错误代码也是一样)
- 从Jared Par 不可能忽略没有专门设计的代码来处理它
这些都是我从思考和google搜索中得出的。我必须承认,在过去几年中,在C#中工作的例外很容易。请进一步说明使用例外情况的原因。对于那些喜欢返回代码的人,我也愿意倾听你的推理。感谢
我认为这个
$ b
- 异常将正常程序流程中的错误处理代码分开,从而使代码更可读,更健壮和可扩展。
- 抛出异常是唯一的
- 异常很容易从深层嵌套的函数中传播出来。
- 异常可以是,通常是用户定义的类型,它们比错误代码包含更多的信息。
- 异常对象与处理程序通过使用类型系统。
使用例外的参数
- 异常通过创建多个不可见的退出点,使代码难以阅读和检查,从而破坏代码结构。
- 异常容易导致资源泄露,
- 学习编写异常安全代码很困难。
- 异常代价昂贵,违反承诺只支付
- 异常很难引入旧代码。
- 异常很容易被滥用来执行属于正常程序流程的任务。
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 -
- 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
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.
Arguments for Using Exceptions
- Exceptions separate error-handling code from the normal program flow and thus make the code more readable, robust and extensible.
- Throwing an exception is the only clean way to report an error from a constructor.
- Exceptions are hard to ignore, unlike error codes.
- Exceptions are easily propagated from deeply nested functions.
- Exceptions can be, and often are, user defined types that carry much more information than an error code.
- Exception objects are matched to the handlers by using the type system.
Arguments against Using Exceptions
- Exceptions break code structure by creating multiple invisible exit points that make code hard to read and inspect.
- Exceptions easily lead to resource leaks, especially in a language that has no built-in garbage collector and finally blocks.
- Learning to write exception safe code is hard.
- Exceptions are expensive and break the promise to pay only for what we use.
- Exceptions are hard to introduce to legacy code.
- Exceptions are easily abused for performing tasks that belong to normal program flow.
这篇关于C ++ - 返回代码异常的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!