异常与断言 [英] Exception Vs Assertion

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

问题描述

Java异常处理和使用断言条件有什么区别?

What is the difference between Java exception handling and using assert conditions?

众所周知,Assert属于两种类型。但是什么时候我们应该使用断言关键字?

It's known that Assert is of two types. But when should we use assert keyword?

推荐答案

使用内部断言代码中的逻辑检查,以及直接代码控制之外的错误条件的正常异常。

Use assertions for internal logic checks within your code, and normal exceptions for error conditions outside your immediate code's control.

不要忘记断言可以打开和关闭 - 如果你关心参数验证之类的东西,应该使用异常显式。 (但是,您可以选择使用断言对私有方法执行参数验证,理由是此时的违规是由内部错误而非外部错误引起的。)

Don't forget that assertions can be turned on and off - if you care about things like argument validation, that should be explicit using exceptions. (You could, however, choose to perform argument validation on private methods using assertions, on the grounds that a violation at that point is due to an internal bug rather than an external error.)

或者,对所有事情都使用例外是完全合理的(IMO)。我个人根本没有使用断言,但这在某种程度上是个人偏好的问题。 (当然可以存在支持和反对断言的客观论据,但它并不足以明确地删除偏好。)

Alternatively it's entire reasonable (IMO) to use exceptions for everything. I personally don't use assertions much at all, but it's a matter of personal preference to some extent. (There can certainly be objective arguments for and against assertions, but it's not sufficiently clear cut to remove preference altogether.)

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

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