Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch and final variables [duplicate]

I have a very silly question for you :)

For example, I have following code snippet:

class MyClass {

    public static void main (String[] args) {

        final String status;

        try {
            method1();
            method2();
            method3();
            status = "OK";
        } catch (Exception e) {
            status = "BAD"; // <-- why compiler complains about this line??
        }

    }

    public static void method1() throws Exception {
        // ...
    }

    public static void method2() throws Exception {
        // ...
    }

    public static void method3() throws Exception {
        // ...
    }

}

The question is inside: why compiler complains about this line?

IntelliJ IDEA says, that Variable 'status' might already have been assigned to.

But, as I can see, we don't ever reach line (where we set status = "OK") in case of exceptional situation. So the status variable will be BAD and everything should be ok. And if we don't have any exception, then we get OK. And we will set this variable only ONCE a time.

Any thoughts about this?

Thanks for your help!

like image 815
Developer87 Avatar asked Jun 29 '15 18:06

Developer87


2 Answers

The Java compiler doesn't see what you and I see -- that either status gets set to "OK" or it gets set to "BAD". It assumes that status can be set and an exception is thrown, in which case it gets assigned twice, and the compiler generates an error.

To workaround this, assign a temporary variable for the try-catch block, and assign the final variable once afterwards.

final String status;
String temp;

try {
    method1();
    method2();
    method3();
    temp = "OK";
} catch (Exception e) {
    temp = "BAD";
}

status = temp;
like image 166
rgettman Avatar answered Nov 12 '22 23:11

rgettman


What if the code that caused the exception occured after status = "OK"? The reason you get the error seems pretty obvious.

Take this for example:

final String status;

try {
    status = "OK":
    causeException();
}catch(Exception e) {
    status = "BAD";
}

void causeException() throws Exception() {
    throw new Exception();
}

This would result in reassigning the variable, which is why you get an error.

like image 35
Vince Avatar answered Nov 12 '22 21:11

Vince