Java catch block, caught exception is not final

前端 未结 4 1049
长发绾君心
长发绾君心 2021-02-04 07:05

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

4条回答
  •  孤独总比滥情好
    2021-02-04 07:39

    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.

提交回复
热议问题