I am checking out the new features of Java SE7 and I am currently at this point:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
The reason I can think of to enforce it final is due to performance. Once the catch evaluation starts, having a final immutable value in the mechanics of the evaluation ensures a faster evaluation of all catches. Since try-catch is extensively used throughout any java code, the highest performance design is preferable.
Based on the above, it implies a performance improvement that affects most programs.
The idea behind exception-based error handling is that each error should be recovered, if at all possible, at the appropriate level of abstraction. Such error recovery might require information that is not directly available where the exception is actually handled. For this reason it might be convenient to catch the exception, augment it with the relevant information and rethrow it or possibly set it as cause of a new exception object of a more appropriate class.
I cannot think of a convincing use-case for modifying an exception in a classic catch
clause. However, that doesn't mean it should be forbidden. Especially given that you can modify a parameter variable. If you find this worrisome, you have the option of declaring the exception variable to be final
.
On the other hand, allowing modification in the multi-exception catch would introduces the possibility of truly bizarre and confusing code such as this:
catch (IOException | NullPointerException ex) {
...
ex = new IllegalArgumentException(...);
}
I imagine that's what the designers had in mind when they added the restriction in this case.
But either way, this is how the Java language is defined, and what we have to live with. There's not a lot of point in debating the apparent inconsistencies ... unless you are intending to design and implement a new language.
It's pretty much the same as method arguments:
You usually don't modify them and many people agree that they should be treated as final
(whether or not to actually write final
in front of them is a matter of some debate).
But since there's no technical requirement that says it must be final
, the language gives you the option to choose.
Personally I know of no good reason to modify the exception reference of a catch-block.