简体   繁体   中英

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.

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 .

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