WVrock
WVrock

Reputation: 1765

Might not have been initialized error at null check

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?

Upvotes: 9

Views: 4774

Answers (2)

B. Kemmer
B. Kemmer

Reputation: 1537

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

final Reader reader;

to

Reader reader = null;  

and give reader a initial value.

Upvotes: 1

Eran
Eran

Reputation: 393936

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.

Upvotes: 14

Related Questions