Skip to content
Advertisement

How to resolve findbug issue: Null passed for nonnull parameter

I’m getting the following findbugs error:

“Method call passes null for nonnull parameter : Null passed for nonnull parameter of getApiStatus(ApiResponse)”

If the apiResponse is null in the CallApi method (not shown here for brevity’s sake), it simply throws an exception that is caught in handleApiException and thrown again if we can’t do anything else about the exception.

There is no way that a null value for apiResponse could be passed into getApiStatus() method at the botton of this code snippit. How can I tell findbugs that this is the case without doing yet another null check on top of the null check that is done in the apiService.CallApi method? I’ve tried using the NonNull annotation, but that didn’t resolve the issue. Here’s the code in question:

ApiResponse apiResponse = null;
try {
    apiResponse = apiService.CallApi(apiURL, requestObject);
}
catch (ApiException ex) {
    handleApiException(ex);
}

boolean apiStatus = getApiStatus(apiResponse);

Any Ideas?

Advertisement

Answer

My suggestion would be to NOT handle the exception, but to set this method as throws ApiException. And then handle it higher up the chain. If your code gets an exeption in that try block, then handles the exception in the catch, then apiResponse can easily be null. And will then go on to try the getApiStatus method, hence passing in a null.

public void yourMethod() throws ApiException {
    ApiResponse apiResponse = apiService.CallApi(apiURL, requestObject);
    boolean apiStatus = getApiStatus(apiResponse);
    // Whatever else you need to do here.
}

Your only other option is to put the apiStatus call below the apiResponse one inside the try block, like so:

ApiResponse apiResponse = null;
try {
    apiResponse = apiService.CallApi(apiURL, requestObject);
    boolean apiStatus = getApiStatus(apiResponse);
} catch (ApiException ex) {
    handleApiException(ex);
}

Or, as you say, do a null check before calling getApiStatus, but that’s not as preferable as the options above.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement