Java - Return statement and thrown exception using method inside catch block?

后端 未结 5 1833
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 15:40

I have following code using hibernate to throw a custom exception on error and I also want to close the session in this case, since the exception won\'t be catched unless receiv

5条回答
  •  半阙折子戏
    2021-01-21 16:09

    This is the problem with methods like closeSessionAndThrow. The JLS rules do not allow the compiler to infer that since the method unconditionally throws an exception it can never return normally. The calling code therefore has to be written as if the method could return ... even though "we know" it cannot happen.

    You simply have to go with the flow. This is an "unusual" control pattern that the Java language doesn't support as well as you / we would like.


    (Under certain circumstances, one can prove that the method will always throw an exception under certain assumptions. However, since the method is public and in a different class, one of the assumptions is that the classes that define and use the method won't be changed and compiled independently of each other. Of course, that is not the kind of assumption that a compiler can make ... and it partly explains why the JLS rules don't attempt to cover this pattern.

    If they were to "fix" this problem, it would require something like an annotation, or change to the java syntax to declare that the helper method cannot return.)

提交回复
热议问题