3 ms·
Of course. But Java could recognize if any potentially-throwing code is executed within the try block after the assignment, similar to how it tracks where check
by layer8 4y ago
Of course. But Java could recognize if any potentially-throwing code is executed within the try block after the assignment, similar to how it tracks where checked exceptions are being thrown.
Meaning, when needed you could still always do:
final Foo foo;
try {
Foo tmpFoo = bar(baz);
otherFunction();
foo = tmpFoo;
} catch (SomeException ex) {
foo = SOME_DEFAULT;
}
But at present the "best" (besides introducing a separate method) you can do is
final Foo foo;
Foo tmpFoo;
try {
tmpFoo = bar(baz);
otherFunction();
} catch (SomeException ex) {
tmpFoo = SOME_DEFAULT;
}
foo = tmpFoo;
Which has the drawbacks that (a) the compiler doesn't check that tmpFoo is assigned exactly once (because you can't make it final), and (b) tmpFoo stays around for the rest of the scope, with the risk of being misused later.
I would understand if an excemption is being made for Errors, because in princible any JVM bytecode instruction could probably throw one, but not for regular Exceptions.