开发者

How to make this variable reference `final`, how do I get this to compile cleanly?

I want to make the result variable final, how do I structure this code so that this compiles cleanly? I know I have done this in the past, but I can't remember how I structured it to make it work.

The following code is a straw man example, the code I am trying to clean up is much more complicated, this is just开发者_运维百科 distilling the essence of what I am trying to accomplish.

private boolean someMethod()
{
    final boolean result;
    try
    {
        // do the logic here that might throw the following
        // exceptions
    }
    catch (final IOException ioe)
    {
        result = false;
    }
    catch (final ClassNotFoundException cnfe)
    {
        result = false;
    }

    return result;
}

I can't put the result = true in the try block because it won't compile with both the catch blocks complaining that the final variable might already be assigned.

I can't put it in a finally block because that would generate the same complaints as in the try block?

I want to be able to set result = once and only once.

So where do you set result = true; to get it to compile cleanly?


It's a lot simpler to not set a variable.

private boolean someMethod() {
    try {
        // do the logic here that might throw the following
        return true;

    } catch (IOException ioe) {
        // handle IOE
    } catch (ClassNotFoundException cnfe) {
        // handle CNFE
    }
    return false;
}


Trying to use final to enforce "assign exactly once" is always tricky. You can use a second variable:

private boolean someMethod()
{
    boolean res;
    try
    {
        // do the logic here that might throw the following
        // exceptions
    }
    catch (final IOException ioe)
    {
        res = false;
    }
    catch (final ClassNotFoundException cnfe)
    {
        res = false;
    }
    final boolean result = res;
    return result;
}

But the real question is, why not just remove the final qualifier?


You cannot reassign a value to a final variable, so this is impossible.

edit: It's also a contradiction to want to declare a variable that is local to a method as final and also change the value in the same method - why is it necessary to declare it as final at all in this method?


If you declare a local variable as final within a method then the value of that variable cannot be changed within the method.

Remove the final from the declaration of result, or get rid of the result local variable altogether and return directly from within the catch blocks and the end of the method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜