0

Java provides to catch multiple exceptions in single catch block. but this is confusing for me. how can I know which exception is caught in this block ? and normally a variable in java has only one type. so how can e variable have too many types ?

Example

try {
    // codes
    // ...
    // ..
    // .
} catch(InturreptedException | FileNotFoundException | AnotherException e) {
    // how can I know what the type of `e` is ?
}
1 JustOnly 1
  • 171
  • 11
  • 6
    *If* you need to know the type of `e` you probably should not use a multi-catch. – luk2302 Feb 21 '18 at 18:38
  • that seems reasonable. Also, you can also use the instance of test in an if block, in case you need something minor for a given type. – Victor Feb 21 '18 at 18:40

1 Answers1

1

e type is the most specific common supertype of the throwable types listed in the multi-catch clause.

If AnotherException is some subtype of Exception, then in your case it will be Exception, because InterruptedException and FileNotFoundException have Exception as the most specific common supertype.

More precisely, here is what the specification says:

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).

lub is 'least upper bound' defined in section 4.10.4 of the Java Language Specification: https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72
  • @thanks, for example: if all exception types in multi-catch clause have `IOException` super type, so type of `e` is `IOException`. right ? – 1 JustOnly 1 Feb 21 '18 at 18:42
  • @1JustOnly1 If they all have `IOException` as supertype, and no class exists such that it extends `IOException` and it is extended by all the alternatives in a multi-catch, then yes, `IOException` is the type of `e`. – Roman Puchkovskiy Feb 21 '18 at 18:45