如何在这段代码中处理空指针异常?

huangapple go评论90阅读模式
英文:

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

问题

我们在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();
    }
}

我的主管告诉我它可能会引发一个未处理的“空指针异常”,但我不明白如何修复它。我已经使用了trycatch,所以我不确定可能出什么问题。有人知道可能出什么问题吗?我感激任何帮助 如何在这段代码中处理空指针异常?

英文:

We have the following snippet of code in Spring-Boot:

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

private final ImageValidationProperties imageValidationProperties;

public ImageResponse getImageslistFromCloud(String image, Integer cloud) {
	String imageNumber = &quot;0RC&quot;;
	String url = imgUrl;
	if (cloud != null) {
		imageNumber = imageValidationProperties.getImagesFromCloud(cloud);
		url = imageValidationProperties.getUrlFromCloud(cloud);
	}
	log.debug(&quot;Request images&quot;, imageNumber);
	ResponseEntity&lt;ImageResponse&gt; 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(&quot;error: {}&quot;, 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 如何在这段代码中处理空指针异常?

答案1

得分: 1

@Value属性为空,因为您的类没有一个Bean,请尝试使用@ Service,@ Component甚至使用@Bean注解来注释您的类。

英文:

@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.

答案2

得分: 1

你的catch块会在template.getForEntity导致HTTP错误时抛出NullPointerException(例如,如果找不到资源)。在这种情况下,imgResponse仍然为null,然后你调用了它的getBody()方法。相反,你应该返回null或使用Optional作为返回类型,并返回Optional.empty()。

你还应该避免捕获非常常见的Exception,更具体地捕获你想要捕获的异常。

英文:

Your catch block will throw a NullPointerException if template.getForEntity resulted in an HTTP error (e.g. 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.

答案3

得分: 0

try块中,您实例化了imgResponse字段。但是,在catch块中,您直接使用imgResponse.getBody();语句返回响应。这可能会引发NullPointerException

避免NullPointerException的一种最佳方法是使用java.util.Optional。这可以潜在地避免在运行时中断您的代码。

英文:

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.

答案4

得分: 0

我认为问题出在catch块中的imgResponse.getBody()。在catch块中,imgResponse仍然为null,当调用imgResponse.getBody()时将抛出NPE。

另一个地方是:您还需要初始化变量imageValidationProperties,否则它的方法调用将导致空指针异常(imageNumber = imageValidationProperties.getImagesFromCloud(cloud); url = imageValidationProperties.getUrlFromCloud(cloud);)。

英文:

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

huangapple
  • 本文由 发表于 2020年7月29日 20:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63153848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定