FIndbug无法识别空指针异常 [英] FIndbug not identifying null pointer exception

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

问题描述

我正在使用用Eclipse整数化的Findbugs.

I am using Findbugs integerated with eclipse.

当我在项目上运行findbugs时,可能的空指针异常未捕获以下代码.

When I run findbugs on my project the below code is not captured for possible null pointer exception.

在下面的代码段中,对象测试易于出现空指针异常,该异常未被findbugs标识.

In the below snippet the object test is prone to null pointer exception which is not identified by findbugs.

@Override
    public boolean saveIrr(TestObject test) throws DuplicateRecordException {
        boolean status = false
        try {
            test.getAddDate();
            status = adhocMaintPopupMapper.saveIrr(IRRPopupMaint);
        } catch (DataIntegrityViolationException e) {
            logger.error("Error in Saving!", e);
            throw new TransactionDataException("Error in Saving!", e);
        }
        return status;
    }

是否需要进行任何配置更改才能使findbug识别出这一点?

Is there any configuration change required to make findbugs to identify this?

推荐答案

如果将@Nonnull添加到参数声明中,FindBugs将在任何传递未检查null的值的地方突出显示.如果将其标记为@CheckForNull,FindBugs将在您访问该方法的任何位置突出显示,而无需检查null.

If you add @Nonnull to the parameter declaration, FindBugs will highlight anywhere you're passing a value that isn't checked for null. If you mark it @CheckForNull, FindBugs will highlight anywhere in the method that you access it without checking for null.

您的操作取决于方法的约定:它可以容忍null吗?看一下它的实现,它不允许null而不引发意外的异常.因此,应将test标记为@Nonnull,以便可以发现错误的呼叫.

Which you do depends on the method's contract: does it tolerate null or not? Looking at its implementation it does not allow for null without throwing an unexpected exception. Therefore, test should be marked @Nonnull so you can spot incorrect calls.

更新

FindBugs将仅 检查用@Nonnull@CheckForNull注释的字段,参数,方法返回值.假定没有注释的任何内容@Nullable告诉FindBugs忽略它.

FindBugs will only check fields, parameters, method return values that are annotated with either @Nonnull or @CheckForNull. Anything without an annotation is assumed @Nullable which tells FindBugs to ignore it.

public boolean saveIrr(@Nonnull TestObject test) { ... }

public void dontCareAboutNull(TestObject value) {
    saveIrr(value); // no bug
}

public void mightBeNull(@CheckForNull TestObject value) {
    saveIrr(value); // bug
}

由于这个原因,我们在包级别将@Nonnull应用于所有三种类型的值.任何需要允许null的值都必须用@CheckForNull注释.除了极少数情况(例如,Spring强制执行的@Autowired字段)外,我们不允许使用@Nullable.

For this reason, we apply @Nonnull to all three types of values at the package level. Any value that needs to allow null must be annotated with @CheckForNull. We do not allow the use of @Nullable except in very few corner cases (e.g. @Autowired fields which Spring enforces).

这篇关于FIndbug无法识别空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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