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

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

问题描述

大多数情况下,我将使用异常来检查代码中的条件,我想知道什么时候使用断言是适当的时候?



实例,

  Group group = null; 
try {
group = service()。getGroup(abc);
} catch(异常e){
//我不记录错误,因为我知道每当发生错误意味着组未找到
}

if(group!= null )
{
//做某事
}

表明断言如何适应这里?我应该使用断言吗?



似乎我从来没有在生产代码中使用断言,只能在单元测试中看到断言。我知道在大多数情况下,我可以使用异常来做如上所述的检查,但是我想知道适当的方式来专业。

解决方案

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



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



断言会使程序停止运行,但是例外会让程序继续运行。



注意 if(group!= null)不是断言,只是一个有条件的。


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?

For instance,

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.

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.

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

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

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