我得到以下findbugs错误:
"方法调用为nonnull参数传递null:为getApiStatus的nonnull参数(ApiResponse)传递null"
如果CallApi方法中的apiResponse为null(为了简洁起见,这里没有显示),它只会抛出一个在handleApiException中捕获的异常,如果我们不能对该异常执行任何其他操作,则会再次抛出。
apiResponse的null值不可能在这个代码的底部传递到getApiStatus()方法中。在apiService.CallApi方法中进行的null检查之外,如果不进行另一个null检查,我如何告诉findbugs这种情况?我尝试过使用NonNull注释,但这并没有解决问题。这是有问题的代码:
ApiResponse apiResponse = null;
try {
apiResponse = apiService.CallApi(apiURL, requestObject);
}
catch (ApiException ex) {
handleApiException(ex);
}
boolean apiStatus = getApiStatus(apiResponse);
有什么想法吗?
我的建议是不处理异常,而是将此方法设置为throws ApiException。然后在链条的更高位置处理它。如果您的代码在try块中获得exeption,然后在catch中处理异常,那么apiResponse很容易为null。然后将继续尝试getApiStatus方法,从而传入一个null。
public void yourMethod() throws ApiException {
ApiResponse apiResponse = apiService.CallApi(apiURL, requestObject);
boolean apiStatus = getApiStatus(apiResponse);
// Whatever else you need to do here.
}
您唯一的其他选择是将apiStatus调用放在try块中apiResponse调用的下面,如下所示:
ApiResponse apiResponse = null;
try {
apiResponse = apiService.CallApi(apiURL, requestObject);
boolean apiStatus = getApiStatus(apiResponse);
} catch (ApiException ex) {
handleApiException(ex);
}
或者,正如您所说,在调用getApiStatus之前进行null检查,但这不如上面的选项好。
在代码中,无论是否出现ApiException
,都将调用getApiStatus(apiResponse)
。
你应该有这个:
try {
ApiResponse apiResponse = apiService.CallApi(apiURL, requestObject);
// line bellow will not execute if CallApi throws ApiException
boolean apiStatus = getApiStatus(apiResponse);
}
catch (ApiException ex) {
handleApiException(ex);
}
// lines bellow will execute after try-catch block above
// regardless of the ApiException occurring or not
如果CallApi
抛出异常,那么它将被处理,控制将继续到getApiStatus
,而apiResponse
不会被分配除初始null
之外的任何东西。