user177800
user177800

Reputation:

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?

Upvotes: 1

Views: 230

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533660

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;
}

Upvotes: 3

John Topley
John Topley

Reputation: 115372

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.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234847

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?

Upvotes: 2

matt b
matt b

Reputation: 139961

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?

Upvotes: 1

Related Questions