使用例外的参数
- 例外是从正常程序流程中分离错误处理代码,从而使代码更易读,更强大和可扩展。
- 投掷一个例外是从构造函数报告错误的唯一干净的方法。
- 与错误代码不同,异常很难忽略。
- 异常很容易从深度嵌套的函数传播。
- 异常可以是,通常是用户定义的类型,比错误代码携带更多的信息。
- 异常对象通过使用类型系统与处理程序相匹配。
使用例外的参数
- 异常通过创建多个不可见的退出点来破解代码结构,使得代码难以阅读和检查。
- 异常很容易导致资源泄露,特别是在没有内置的垃圾回收器,最后阻止。
- 学习写异常安全代码很难。
- 例外是昂贵的,打破了承诺只支付
- 异常很难引入旧版代码。
- 异常很容易被滥用来执行属于正常程序流的任务。
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屋!