Java:检查null或允许异常处理 [英] Java: check for null or allow exception handling

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

问题描述

我想知道使用try / exception处理空值的成本与使用if语句首先检查空值相比。

I'm wondering about the cost of using a try/exception to handle nulls compared to using an if statement to check for nulls first.

提供更多信息。获得空值的概率大于50%,因为在这个应用程序中。如果没有输入数据,则通常为null ...因此尝试使用null进行计算是司空见惯的。

To provide more information. There's a > 50% chance of getting nulls, because in this app. it is common to have a null if no data has been entered... so to attempt a calculation using a null is commonplace.

这就是说,如果我使用if语句在计算之前先检查null并且不首先尝试计算,或者更少,它会提高性能吗?只是抛出异常并处理它是昂贵的吗?

This being said, would it improve performance if I use an if statement to check for null first before calculation and just not attempt the calculation in the first place, or is less expensive to just let the exception be thrown and handle it?

感谢任何建议: - )

thanks for any suggestions :-)

谢谢伟大的发人深省的反馈!这是一个PSEUDOcode示例,用于澄清原始问题:

Thanks for great thought provoking feedback! Here's a PSEUDOcode example to clarify the original question:

BigDecimal value1 = null //assume value1 came from DB as null
BigDecimal divisor = new BigDecimal("2.0");

try{
    if(value1 != null){ //does this enhance performance?... >50% chance that value1 WILL be null
        value1.divide(divisor);
    }
}
catch (Exception e){
    //process, log etc. the exception
    //do this EVERYTIME I get null... or use an if statement
    //to capture other exceptions.
}


推荐答案

我建议检查null并且不进行计算而不是抛出异常。

I'd recommend checking for null and not doing the calculation rather than throwing an exception.

异常应该是例外而且很少见,不是管理控制流的方法。

An exception should be "exceptional" and rare, not a way to manage flow of control.

我还建议您与客户就输入参数建立合约。如果允许空值拼写出来;如果它们不是,请明确应该传递的内容,默认值以及如果传递空值则保证返回的内容。

I'd also suggest that you establish a contract with your clients regarding input parameters. If nulls are allowed spell it out; if they're not, make it clear what should be passed, default values, and what you promise to return if a null value is passed.

这篇关于Java:检查null或允许异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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