什么时候使用assert()和什么时候使用try catch? [英] When to use assert() and when to use try catch?

查看:348
本文介绍了什么时候使用assert()和什么时候使用try catch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在哪种情况下使用它们?

In which situations do you use them?

推荐答案

尝试... catch-针对例外情况,即不是由格式错误的代码引起的,但可能会改变的情况外部不可预测事件导致的正常控制流.

Try... catch - for exceptional conditions, i.e. conditions which aren't caused by malformed code, but which may just alter the normal control flow by external unpredictable events.

断定捕获无效代码的断言,即检查函数中是否保存了不变式,检查是否使用正确的参数调用了内部方法(对于公共API,您可能仍需要一个异常)等

Assertions for catching invalid code, i.e. checking if an invariant is held in the function, checking if an internal method is called with right arguments (for public API you might still want an exception for that), etc.

这些是我的基本准则,但是约定因情况而异,因语言而异.

Those are my basic guidelines, but the conventions vary from situation to situation and from language to language.

有疑问时,您可以问自己:在我们测试并完成所有操作后,发行代码中是否仍应保留特定的安全检查?如果您回答是,那么仍然有必要",则可能需要例外.否则,您可能需要一个断言.

When you're in doubt, you can ask yourself: is that specific safety check supposed to still be there in the release code, after we test and finish everything? If you answer "yes, it's still neccessary then", you probably want an exception. Otherwise, you probably want an assertion.

这篇关于什么时候使用assert()和什么时候使用try catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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