什么时候使用assert(),什么时候使用try catch?
您在哪些情况下使用它们?
In which situations do you use them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您在哪些情况下使用它们?
In which situations do you use them?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
try-catch和assert的情况完全不同。
断言用于检查您收到的值(例如作为参数)是否符合预期。我不建议在生产代码中使用断言,它主要用于单元测试,很少用于检查参数。
要更好地检查传递的值,请使用以下内容:
当您知道块内的某些内容可能会出错时,请使用 Try-catch 块。例如,您向SD卡写入数据,但没有空间可写入。或者,您碰巧尝试超出数组范围来读取数组。然后,将关键代码放入 try-catch 块中并检查异常:
更多 关于异常和 try-catch 块。
The situations of try-catch and assert are totally different.
Assert is used to check if the value you have received, as parameter for example, is expected. I would not recommend to use assert in production code, it is used in unit-test mostly and rarely to check the parameters.
To check the passed values better to use something like:
Try-catch block is used when you know something inside the block can go wrong. For example, you write to an sdcard and there is no space for writing. Or, it happened that you try to read the array out of it bounds. Then, you put your critical code in try-catch block and check for the excpetions:
More about exceptions and try-catch blocks.
Try...catch - 用于异常情况,即不是由格式错误的代码引起的情况,但可能只是通过外部不可预测的事件改变正常的控制流。
用于捕获无效代码的断言,即检查函数中是否保留不变式,检查是否使用正确的参数调用内部方法(对于公共 API,您可能仍然需要例外)等。
这些是我的基本准则,但惯例因情况和语言的不同而有所不同。
当您有疑问时,您可以问自己:在我们测试并完成所有内容之后,特定的安全检查是否应该仍然存在于发布代码中?如果你回答“是的,那么仍然有必要”,那么你可能想要一个例外。否则,您可能需要一个断言。
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.
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
策略。尽管如此,我喜欢在抛出异常的地方使用assert()。对于我(作为一名开发人员!)来说,通过assert()
消息获取失败行通常比通过异常堆栈更方便。Normally
assert()
does not work in release code, so it can never replace atry-catch
strategy. Nevertheless I like to useassert()
in places where exceptions are thrown. For me (as a developer!), it is often more convenient to get by anassert()
message to the line of failure than through the exception stack.它们是为了不同的目的而创建的。
Assert
更多的是为了发现bug,try-catch
是为了处理异常情况。They are created for different purposes.
Assert
is more for finding bugs,try-catch
is for handling exceptional situations.