A statement from The Java® Language Specification:
An exception parameter of a uni-catch clause is never implicitly declared
final
, but may be effectively final.
What does may be implies here. Please explain with example.
The JLS8 states in section 4.12.4:
A local variable or a method, constructor, lambda, or exception parameter is effectively final if it is not declared final but it never occurs as the left hand operand of an assignment operator (§15.26) or as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).
In the following example, the variable e
is effective final. That means it can be used in lambda expressions and anonymous inner classes:
try {
throw new RuntimeException("foobar");
} catch (RuntimeException e) {
Runnable r = () -> { System.out.println(e); };
r.run();
}
In the following example, the variable e
is not effective final, because there is an assignment to that variable. That means, it can not be used within lambda expressions and anonymous inner classes:
try {
throw new RuntimeException("foo");
} catch (RuntimeException e) {
e = new RuntimeException("bar", e);
Runnable r = () -> { System.out.println(e); }; // ERRROR
r.run();
}