Search code examples
javaexceptionjava-7

Is it possible to catch multiple exceptions and perform different logic upon them without using multiple catch statements?


As to perform different logic upon the exceptions. As following:

catch (IOException e | IllegalArgumentException a) {

       e.doStuff();
       a.doStuff();
    }

Solution

  • That doesn't make sense. When you use a multi catch, then you are implicitly saying: all of "these" exceptions should fall into the same bucket.

    Of course, you can then do some instanceof if/else trees, but heck: the java way of doing that would be to have different catch statements for each one.

    But, also of course, depending on context, it might be pragmatic to do something like

     catch(XException | YException | ZException  xyOrZ) {
       log(xyOrZ);
       handle(xyOrZ);
    

    where handle() does some instanceof "switching".

    Long story short: multi catch is a convenient way to enable an aspect (such as logging) that works for all exceptions. But it can get into your way regarding exception specific handling. You simply have to balance your requirements, and use that solution that your team finds to best fit your needs. To a certain degree, this is about style, and style questions are decided by the people working the code base.