'The local variable XXX may not have been initialized' 错误 - 为什么它出现在我的代码中,而在此示例中却没有?

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

每当我在方法中声明一个局部变量,然后在 if/else 块或 try/catch 等条件中为其赋值,然后尝试 return 变量,我得到编译器错误

The local variable XXX may not have been initialized

我知道 if/else 或 try/catch 块在某些情况下可能不会执行,因此变量不会被初始化,因此会出现错误。

但我经常遇到没有初始化变量但仍然有效的代码。对于example, on this page,见以下方法:

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

当我写同样的方法时,我得到了 return 语句的错误。 我的方法与这个方法的唯一区别是我只有 ifelse-if 块,没有 else 块。

人们是否通过方法上的一些注释或其他方式来抑制此错误,我不这么认为。

那为什么他们没有得到错误,而我却得到了?

之所以有效,是因为当您到达 return 语句时,viewType 保证有一个值。

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

它将有 TYPE_IMAGETYPE_GROUP

在您的代码中,您可能会做一些类似的事情:

     int viewType;
     try{
        // some code which can cause an exception.
        viewType=something;          

     } catch(Exception e){}

     return viewType;

       int viewType;
       if(some condition){
          viewType=something;          
       }
       return viewType;

在这两种情况下,您不能保证 viewType 在到达 return 语句时会有值。

如果 try 块抛出任何异常或条件在您的 if 块中失败,viewType 将没有任何值。

这就是您会收到错误的原因。但是在您发布的代码中并非如此,该代码保证具有一定的价值。