简体   繁体   English

如何处理此代码块中的 Null 指针异常?

[英]How to handle Null Pointer Exception in this block of code?

We have the following snippet of code in Spring-Boot:我们在 Spring-Boot 中有以下代码片段:

@Value("${service.image.cloud.host}")
String imgUrl;

private final ImageValidationProperties imageValidationProperties;

public ImageResponse getImageslistFromCloud(String image, Integer cloud) {
    String imageNumber = "0RC";
    String url = imgUrl;
    if (cloud != null) {
        imageNumber = imageValidationProperties.getImagesFromCloud(cloud);
        url = imageValidationProperties.getUrlFromCloud(cloud);
    }
    log.debug("Request images", imageNumber);
    ResponseEntity<ImageResponse> imgResponse = null;
    try {
        RestTemplate template = new RestTemplate();
        imgResponse = template.getForEntity(url.concat(imageNumber).concat(imgUrl), ImageResponse.class);
        return imgResponse.getBody();
    }
    catch (Exception e) {
        log.error("error: {}", e);
        return imgResponse.getBody();
    }

}

My supervisor told me that it could throw a Null Pointer Exception which is not handled, but I dont understand how it could be fixed.我的主管告诉我,它可能会抛出未处理的Null Pointer Exception ,但我不明白如何修复它。 I have used try and catch already so I am not sure what could go wrong.我已经使用try and catch了,所以我不确定 go 会出现什么错误。 Someone has idea what could be wrong?有人知道可能出了什么问题吗? I apperciate any help:)我感谢任何帮助:)

@Value property is null because your Class doesn't have a Bean, try to annotate your class with @Service, @Component or even use a @Bean annotation. @Value 属性是 null 因为您的 Class 没有 Bean,请尝试使用 @Service、@Component 注释您的 class 甚至使用 @Bean 注释。

Your catch block will throw a NullPointerException if template.getForEntity resulted in an HTTP error (eg if the resource could not be found).如果 template.getForEntity 导致 HTTP 错误(例如,如果找不到资源),您的 catch 块将抛出 NullPointerException。 In this case imgResponse is still null and you call the getBody() method on it.在这种情况下,imgResponse 仍然是 null 并且您在其上调用 getBody() 方法。 Instead you should return null or use Optional as return type and return Optional.empty().相反,您应该返回 null 或使用 Optional 作为返回类型并返回 Optional.empty()。

You should also avoid to catch the very common Exception and be more specific about the exceptions you want to catch.您还应该避免捕获非常常见的异常,并更具体地了解您想要捕获的异常。

In try block you instantiated imgResponse field.But, In catch block you directly returned response by using imgResponse.getBody();在 try block中,您实例化imgResponse字段。但是,在catch块中,您使用imgResponse.getBody(); statement.陈述。 Which will possibly throw NullPointerException .这可能会抛出NullPointerException

One best way to avoid NullPointerException is to use java.util.Optional .避免NullPointerException的一种最佳方法是使用java.util.Optional Which could potential save to break your code at runtime.这可能会节省在运行时破坏您的代码。

I think the problem is with imgResponse.getBody() in the catch block.我认为问题出在 catch 块中的 imgResponse.getBody() 上。 imgResponse is still null in the catch block, which will throw NPE when imgResponse.getBody() is called.在 catch 块中 imgResponse 仍然是 null ,在调用 imgResponse.getBody() 时会抛出 NPE。

Another place is: you need to initialize the variable imageValidationProperties as well, otherwise its method call will result in null pointer exception (imageNumber = imageValidationProperties.getImagesFromCloud(cloud); url = imageValidationProperties.getUrlFromCloud(cloud);)另一个地方是:你还需要初始化变量imageValidationProperties,否则它的方法调用会导致null指针异常(imageNumber = imageValidationProperties.getImagesFromCloud(cloud); url = imageValidationProperties.getUrlFromCloud();)

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

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