posted 18 years ago
Hemant, why are you using the [code] tag for text that's not code at all? It looks very odd.
In the code show, if an exception occurs in the finally block, it will be thrown from the method before it reaches the return statement. So it doesn't matter if the variable a has not been assigned, because we never use a for anything. In contrast, in the second code sample from your first post, the "catch (Exception e)" means that if an exception were somehow thrown from the line a = 2, it would be caught, and then execution would proceed to the "return a". This would be problematic because in this case, a has not been assigned.
[Tony]: It is because a fundamental of Java is that any piece of code may throw an exception (go figure?).
Or at least, for purposes of determining whether a given variable is definitely assigned, the compiler is required to assume that any piece of code might throw a RuntimeException or an Error. That's not quite the same as saying it might actually happen. I'm guessing the rules were written this way because otherwise there would be a slippery slope for compiler authors - how much analysis should be performed to determine whether a given piece of code is reachable, or whether a given variable has been definitely assigned or not? Behavior among compilers would vary significantly depending on how smart they were, and code that was poorly written but functional might pass on one compiler and not on another. Not that there aren't variances between compilers anyway, but I think they'd be much greater if the JLS didn't require certain simplifying assumptions in this particular area.
"I'm not back." - Bill Harding, Twister