何时使用 assert() 以及何时使用 try catch? [英] When to use assert() and when to use try catch?

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

问题描述

你在什么情况下使用它们?

In which situations do you use them?

推荐答案

Try... catch - for exceptional conditions,即不是由格式错误的代码引起的情况,但可能会改变外部不可预测事件的正常控制流程.

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天全站免登陆