何时使用断言以及何时使用异常 [英] When to use an assertion and when to use an exception

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

问题描述

大多数时候我会使用异常来检查代码中的条件,我想知道什么时候是使用断言的合适时机?

Most of the time I will use an exception to check for a condition in my code, I wonder when it is an appropriate time to use an assertion?

例如,

Group group=null;
try{
    group = service().getGroup("abc");
}catch(Exception e){
    //I dont log error because I know whenever error occur mean group not found
}

if(group !=null)
{
    //do something
}

您能否指出一个断言如何适合这里?我应该使用断言吗?

Could you indicate how an assertion fits in here? Should I use an assertion?

似乎我从不在生产代码中使用断言,只在单元测试中看到断言.我知道在大多数情况下,我可以使用异常来进行上述检查,但我想知道专业"的适当方法.

It seems like I never use assertions in production code and only see assertions in unit tests. I do know that in most cases, I can just use exception to do the checking like above, but I want to know appropriate way to do it "professionally".

推荐答案

断言应该用于检查不应该发生的事情,而异常应该用于检查可能发生的事情.

Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen.

例如,一个函数可能除以 0,因此应该使用异常,但可以使用断言来检查硬盘驱动器是否突然消失.

For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.

断言会阻止程序运行,但异常会让程序继续运行.

An assertion would stop the program from running, but an exception would let the program continue running.

请注意,if(group != null) 不是断言,它只是一个条件.

Note that if(group != null) is not an assertion, that is just a conditional.

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

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