In a Java 7 multicatch block what is the type of the caught exception?

我的梦境 提交于 2019-11-26 17:34:15

问题


In a Java 7 multicatch block such as the following:

try {
    // code that throws exception
} catch (CharacterCodingException | UnknownServiceException ex) {
    // handle exception
}

what is the compile-time type of ex? Is it the most derived class that both exception types have in common? In this example that would be an IOException.


回答1:


Yes, the type of ex is the most specific supertype of both CharacterCodingException and UnknownServiceException, which would be IOException.

Edit: Straight from the horse's mouth on http://cr.openjdk.java.net/~darcy/ProjectCoin/ProjectCoin-Documentation-v0.83.html#multi_catch:

Informally, the lub (least upper bound) is the most specific supertype of the types in question.




回答2:


In JSL 7 http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20-510

§14.20 > The declared type of an exception parameter that denotes its type as a union with alternatives D1 | D2 | ... | Dn is lub(D1, D2, ..., Dn) (§15.12.2.7).

The definition of lub() i.e. the least upper bound is quite convoluted. Fortunately types we are talking about here are usually simply non generic subclasses of Throwable, and lub() yields the most specific super class.

For a more complicated case, consider

class E1 extends Exception implements G<A>
class E2 extends Error implements G<B>

lub(E1, E2) = Throwable & G<?>


来源:https://stackoverflow.com/questions/8393004/in-a-java-7-multicatch-block-what-is-the-type-of-the-caught-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!