vendredi 24 juillet 2015

'The local variable XXX may not have been initialized' error - why does it arise in my code, while doesn't in this example?

Whenever I declare a local variable in a method and then assign values to it in a conditional like if/else block or try/catch, and then try to return the variable, I get the compiler error

The local variable XXX may not have been initialized

I understand that the if/else or try/catch block might not be executed under certain conditions, and so the variable will not be initialized, and thus the error.

But more often than not, I come across code in which they do not initialize the variable and still it works. For example, on this page, see the following method:

public int getItemViewType ( int position ) {
        int viewType;
        if ( groups.get ( position ).getImagePath () != null ) {
            viewType = TYPE_IMAGE;
        } else {
            viewType = TYPE_GROUP;
        }
        return viewType;
    }

When I wrote the same method, I got the error on the return statement. The only difference of my method from this one is that I have only if and else-if blocks, and no else block.

Do people suppress this error through some annotation on the method or something, I don't think so.

So why don't they get the error, while I do?

Aucun commentaire:

Enregistrer un commentaire