Might not have been initialized error at null check

拜拜、爱过 提交于 2019-12-22 04:32:29

问题


I'm checking if the variable is initialized but at that point netbeans is giving me variable reader might not have been initialized warning. How do I fix/suppress this?

This is my code (summary):

final Reader reader;
try {
        reader = new Reader(directory);
        //additional stuff that can cause an exception
    } catch (Exception ex) {
        //do stuff
    } finally {
        if (reader != null);
    }

The point of the if check is to determine whether it is initialized.

And what is the best practice for this?


回答1:


If reader was never initialized, it doesn't even have a null value.

change

final Reader reader;

to

Reader reader = null;

to make sure it has an initial value.

This way, if reader = new Reader(directory); throws an exception, reader will contain null when tested by the finally block.




回答2:


You can't reassign a finale Variable! You gotta change your

final Reader reader;

to

Reader reader = null;  

and give reader a initial value.



来源:https://stackoverflow.com/questions/30702904/might-not-have-been-initialized-error-at-null-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!