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

查看:40
本文介绍了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;
    }

是否需要更改配置才能使 findbugs 识别此问题?

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

推荐答案

如果您将 @Nonnull 添加到参数声明中,FindBugs 将突出显示您传递未经检查的值的任何地方<代码>空.如果您将其标记为 @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 注释.我们不允许使用 @Nullable 除非在极少数情况下(例如 Spring 强制执行的 @Autowired 字段).

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天全站免登陆