例外与断言? [英] Exception vs Assert?

查看:93
本文介绍了例外与断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


在决定使用异常而不是断言时是否有遵循的经验法则(反之亦然)。现在,我只会在运行时在用户端发生某些事情(例如套接字或文件错误)时才抛出异常。



此外,如果我要抛出一个断言,那么抛出一个好的标准对象是什么呢? IIRC有std :: logic_error,但这不是抛出的好对象吗?对于丢失的文件或意外的输入(例如从命令行而不是前端应用程序),我将抛出什么?

解决方案

我的经验法则:



异常用于运行时错误情况(IO错误,内存不足,无法获得数据库连接等)。 / p>

断言用于编码错误(此方法不接受null,开发人员无论如何都通过了)。



<对于具有公共类的库,请在公共方法上引发异常(因为这样做是有道理的)。断言是用来捕获您的错误的,而不是错误。



编辑:由于空值示例,这可能并不十分清楚。我的观点是,对断言永远不会发生的条件(绝不应该将其纳入生产代码的条件)使用断言(正如其他人所指出的那样)。这些条件绝对不能在单元测试或QA测试中失败。


Possible Duplicate:
design by contract tests by assert or by exception?

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.

这篇关于例外与断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆