简体   繁体   English

如何在java中抑制空指针访问警告?

[英]How to suppress null pointer access warning in java?

I am using eclipse IDE.我正在使用 Eclipse IDE。

I have a code which throws NullPointerException and I am handling the exception using try/catch block我有一个抛出NullPointerException的代码,我正在使用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 -在具有identifier length的行上的try block ,我收到警告 -

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 -在具有identifier length的行上,我遇到了错误 -

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 -感谢@Slaw 对此答案的评论 -

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 .在这里,正如@Slaw 所建议的,我确保variable name有可能不是null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM