简体   繁体   中英

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

We have the following snippet of code in 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. I have used try and catch already so I am not sure what could go wrong. 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.

Your catch block will throw a NullPointerException if template.getForEntity resulted in an HTTP error (eg if the resource could not be found). In this case imgResponse is still null and you call the getBody() method on it. Instead you should return null or use Optional as return type and return 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(); statement. Which will possibly throw NullPointerException .

One best way to avoid NullPointerException is to use 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. imgResponse is still null in the catch block, which will throw NPE when imgResponse.getBody() is called.

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);)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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