Why is it legal to re-throw a Throwable in certain cases, without declaring it?

后端 未结 3 1045
长发绾君心
长发绾君心 2020-12-09 03:08

I would expect the following code to raise a compile-time error on throw t;, because main is not declared to throw Throwable, but it c

3条回答
  •  天涯浪人
    2020-12-09 03:37

    This is covered by JLS 11.2.2 (emphasis mine):

    A throw statement whose thrown expression is a final or effectively final exception parameter of a catch clause C can throw an exception class E iff:

    • E is an exception class that the try block of the try statement which declares C can throw; and

    • E is assignment compatible with any of C's catchable exception classes; and

    (...)

    In other words, E, the type referenced in the doc, is the type that can be thrown, not the type of the catch clause parameter that catches it (the catchable exception class). It just has to be assignment compatible to the catch clause parameter, but the parameter's type is not used in analysis.

    This is why the go out of their way to say a final or effectively final exception parameter--if t in your example were reassigned, the analysis would go out the window.

提交回复
热议问题