使用断言还是引发异常? [英] Use an assert or throw an exception?

查看:70
本文介绍了使用断言还是引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有IsValid()方法的类,如果该对象仍然有效,则该方法返回true,否则返回false.该对象最初是有效的,但由于某些外部事件而可能变得无效.

该类具有其他方法,但前提是必须先调用IsValid()返回true,然后才能调用这些方法.处理此先决条件冲突的正确方法是什么?我应该使用断言还是引发异常?

我的第一个直觉是使用断言.但是,对象的有效性由于外部事件而改变.如果在调试期间此事件从未发生,则断言将永远不会被触发.但是,如果它在发行版本中发生,则肯定不会继续触发该断言,因为它将被编译出来.

异常看起来像是这里的答案,但是我希望您能收到更多的意见...

解决方案

异常:至少,您可以通过这种方式对其进行记录并获得一些指示,问题,而不是仅仅掩盖它,并希望它以后不会造成严重的问题.


除此以外,还有其他选择,痛苦就在眼前. blockquote>

不确定我会使用哪种方式-您描述事物的方式,似乎该对象在正常执行期间会进入无效状态,因此取决于退出调用树的难易程度,我会考虑使用返回值来指示未按计划进行.

当您在c ++中使用异常时,您其余的代码也必须能够处理这种情况-就像使用auto_ptr<> (或类似的东西)来保存对动态分配的元素的引用,并以其他方式保护您的程序避免资源泄漏.如果您一直以来都在考虑这一点,那就太好了-然后我想我会选择exceptons,因为它可能需要较少的工作:)

最好的问候
Espen Harlinn


I have a class with a IsValid() method that returns true if the object is still valid or false if not. The object starts out valid but can become invalid due to some external event.

The class has other methods with the precondition that IsValid() should return true before those methods can be invoked. What would be the proper way to handle this precondition violation? Should I use an assert or throw an exception?

My first instinct is to use an assert. However, the validity of the object changes due to an external event. If during debugging this event never happens, the assert will never get triggered. However, if it happens in a release build the assert still won''t get triggered because it would''ve been compiled out.

Exceptions look like the answer here, but I would appreciate more opinions ...

解决方案

Exception: At least that way you can log it and get some indication there is a problem, rather than just masking it and hoping it doesn''t create a serious problem later on.


Go with the exception, with the other option, pain is on the horizon.


Not sure I would use either - the way you describe things, it seems that the object can enter an invalid state during normal execution, so depending on how hard it is to back out of the call tree, I would consider using return values to indicate that something was not proceeding as planned.

When you use exceptions in c++, the rest of your code must also be able to deal with this – like using auto_ptr<> (or something similar) to hold references to dynamically allocated elements, and otherwise protect your program from leaking resources. If you''ve thought of this all along, that''s great - then I guess I would go for exceptons since it probably requires less work :)

Best regards
Espen Harlinn


这篇关于使用断言还是引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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