问题描述
在决定使用异常而不是断言时是否有遵循的经验法则(反之亦然)。现在,我只会在运行时在用户端发生某些事情(例如套接字或文件错误)时才抛出异常。
此外,如果我要抛出一个断言,那么抛出一个好的标准对象是什么呢? IIRC有std :: logic_error,但这不是抛出的好对象吗?对于丢失的文件或意外的输入(例如从命令行而不是前端应用程序),我将抛出什么?
我的经验法则:
异常用于运行时错误情况(IO错误,内存不足,无法获得数据库连接等)。 / p>
断言用于编码错误(此方法不接受null,开发人员无论如何都通过了)。
编辑:由于空值示例,这可能并不十分清楚。我的观点是,对断言永远不会发生的条件(绝不应该将其纳入生产代码的条件)使用断言(正如其他人所指出的那样)。这些条件绝对不能在单元测试或QA测试中失败。
Is there a rule of thumb to follow when deciding to use exceptions instead of asserts (or vice versa). Right now I do only throw if its something I think will happen during runtime on the user side (like a socket or file error). Almost everything else I use asserts.
Also, if I were to throw an assert, what is a nice standard object to throw? IIRC there is std::logic_error but that is not a good object to throw? what would I throw for a missing file or unexpected input (such as from the command line instead of a frontend app)?
My rule of thumb:
Exceptions are used for run-time error conditions (IO errors, out of memory, can't get a database connection, etc.).
Assertions are used for coding errors (this method doesn't accept nulls, and the developer passed one anyway).
For libraries with public classes, throw exceptions on the public methods (because it makes sense to do so). Assertions are used to catch YOUR mistakes, not theirs.
EDIT: This may not be entirely clear, due to the null value example. My point is that you use assertions (as others have pointed out) for conditions that should NEVER happen, for conditions that should NEVER make it into production code. These conditions absolutely must fail during unit testing or QA testing.
这篇关于例外与断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!