multi-catch vs. multiple type patterns in a single case label

Tobias Gierke tobias.gierke at code-sourcery.de
Fri Apr 8 14:03:29 UTC 2022


Hello,

Having read through JEP-420, I wonder why

     try {
         .... do stuff ....
     } catch( IOException | IllegalStateException e) {
         System.out.println("Something went wrong: "+e);
     }

is valid but

     Exception x = ....
     switch(x) {
          case IOException | TimeoutException e -> 
System.out.println("Something went wrong: "+e);
     }

is not. I get that something like

     Exception x = ....
     switch(x) {
          case IOException a, IllegalStateException b ->  .....
     }

would leave one of the variables undefined but why can't I bind multiple 
type patterns to the same variable, have the compiler infer a common 
super-type and use that to check the switch branch ?

Regards,
Tobias



More information about the discuss mailing list