繁体   English   中英

调用方法时处理空指针异常

[英]Handle null pointer exception when calling methods

我有一种情况,当我在许多服务中调用方法时。


    private AmazonS3 getS3Amazon(String access, String secret){
        AmazonS3 amazonS3 = null;
        try {

            amazonS3 = AmazonS3ClientBuilder.standard()
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http...", "us-west-1"))
                    .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(access, secret)))
                    .build();
            Assert.isTrue(amazonS3 != null, "amazonS3 is null");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return amazonS3;
    }

在这种方法中,我在Assert.isTrue(amazonS3 != null, "amazonS3 is null");检查null Assert.isTrue(amazonS3 != null, "amazonS3 is null");

现在在其他方法中,当我必须调用getS3Amazon


public JsonObject createS3Something( Map<String, String>params) {
        //code

       AmazonS3 amazonS3 = this.getS3Amazon(params.get("access"), params.get("secret"));

       //other code using amazonS3
       amazonS3.doSomething();

       return response;
}

为什么我收到“可能抛出“ NullPointerException”的警告”?

我知道我可以在createS3Something检查amazonS3 != null ,但是当我在createS3Something检查null时是否有必要? 在这种情况下最好的方法是什么?

该语句Assert.isTrue(amazonS3 != null, "amazonS3 is null"); amazons3为null时,即当boolean表达式的值为false ,将抛出IllegalArgumentException ,在您的情况下,当amazonS3null

将在随后的catch块中捕获并处理异常,并且amazonS3对象仍将指向null

既然已经处理了异常,那么return语句将把null值返回给调用方。

这就是为什么您收到该警告。

您可以稍微调整代码以使用Optional<AmazonS3>

 private Optional<AmazonS3> getS3Amazon(String access, String secret){
        AmazonS3 amazonS3 = null;
        try {    
            amazonS3 = AmazonS3ClientBuilder.standard()
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http...", "us-west-1"))
                    .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(access, secret)))
                    .build();

        } catch (Exception e) {
            throw e;
        }
        return Optional.ofNullable(amazonS3);
    }

在客户端代码中,只需检查该值是否为null / non-null并使用Optional.ifPresent()

public JsonObject createS3Something( Map<String, String>params) {
        //code
       Optional<AmazonS3> amazonS3 = this.getS3Amazon(params.get("access"), params.get("secret"));

       //other code using amazonS3
       amazonS3.ifPresent(s3 -> s3.doSomething());

       return response;
}

您有一个警告,因为Java不能“理解”该实现

Assert.isTrue(amazonS3 != null, "amazonS3 is null");

正在检查null-基本上为什么要这样做? isTrue方法内部,无论此方法具有什么名称,都可以是任何东西

您可以添加到方法

@SuppressWarnings("ConstantConditions")

但基本上最好在createS3Something检查空值,而不是使用Assert因为此机制更适合于Tests

amazonS3null时,您到底想发生什么?

大多数实践会说让null返回并使用使用方法对其进行检查,然后决定要对此做些什么。

您应该希望所有消耗您代码的代码都知道何时出了问题。 这就是为什么存在异常,并且如此众多的库将它们置于顶层的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM