28

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.

PypeBros
  • 2,607
  • 24
  • 37
Andrew
  • 7,286
  • 3
  • 28
  • 38
  • 1
    it would make sense to be whichever is thrown, but you can easily check by printing out `ex.getClass()` – Jon Egeland Dec 05 '11 at 22:51
  • If you need to have different behavior based on what the caught exception is, then you shouldn't be using a multicatch block - break it out into multiple catch blocks. – Nate W. Dec 05 '11 at 22:52
  • 2
    @Jon: "Type" is a compile-time concept, you're talking about the runtime class of the object. – ColinD Dec 05 '11 at 22:57
  • @Jon: I'd like to know the compile time type of `ex`, not the type at run time. – Andrew Dec 05 '11 at 22:57
  • 1
    @Shakedown I don't want different behaviour; I'd just like to know the type of the exception. – Andrew Dec 05 '11 at 22:58

2 Answers2

28

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.

gustafc
  • 28,465
  • 7
  • 73
  • 99
  • Do you have any references? The [Oracle doc](http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html) seems rather light. – Andrew Dec 05 '11 at 23:00
  • Thanks. Accepted answer it is. – Andrew Dec 05 '11 at 23:13
  • 2
    For future reference: `lub` computation definition is here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.7 – Dariusz Aug 27 '15 at 06:57
14

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<?>
irreputable
  • 44,725
  • 9
  • 65
  • 93