Might not have been initialized error at null chec

2019-04-26 20:53发布

问题:

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.