Payel Senapati
Payel Senapati

Reputation: 1376

How to suppress null pointer access warning in java?

I am using eclipse IDE.

I have a code which throws NullPointerException and I am handling the exception using try/catch block

This is my code -

        String name = null;
        int length = 0;

        try {
            length = name.length();
            System.out.println("Number of letters in name: " + length);
        } catch(NullPointerException e) {
            System.out.println("NullPointerException occured");
        }

        System.out.println("I am being executed");

within the try block on the line having identifier length I am having the warning -

Null pointer access: The variable name can only be null at this location

I am trying to suppress the warning by using -

            @SuppressWarnings("all")
            length = name.length();

Here on the line having identifier length I am having the error -

Multiple markers at this line -
- Syntax error on token "length", VariableDecalaratorId expected after this token
- Null pointer access: The variable name can only be null at this location
- length cannot be resolved to a type

How to resolve this problem?

I don't want my program to show this warning as I am aware of what I am doing.

Upvotes: 1

Views: 1862

Answers (2)

Daniel Butcher
Daniel Butcher

Reputation: 1

Add the following annotation to either the method or class to suppress warnings about potential NullPointerExceptions being thrown. This works in Intellij, although I am unsure about Eclipse.

@SuppressWarnings("DataFlowIssue")

Upvotes: 0

Payel Senapati
Payel Senapati

Reputation: 1376

Thanks to the comment by @Slaw for this answer -

I modified my code in the following way -

        String name = null;
        int length = 0;

        boolean flag = false;
        if(flag) {
            name = "abcd";
        }

        try {

            length = name.length();
            System.out.println("Number of letters in name: " + length);
        } catch(NullPointerException e) {
            System.out.println("NullPointerException occured");
        }

        System.out.println("I am being executed");

Now I longer have the warning.

Here, as suggested by @Slaw I made sure that the variable name has a chance of not being null.

Upvotes: 1

Related Questions