If you can, always use separate catch blocks for individual types of exceptions, otherwise there is no excuse:
} catch (NotAnInt e) { // handle NotAnInt } catch (ParseError e) { // handle ParseError }
... if you do not need to share some general steps and not use additional methods for brevity:
} catch (NotAnInt | ParseError e) { // a step or two in common to both cases if (e instanceof NotAnInt) { // handle NotAnInt } else { // handle ParseError } // potentially another step or two in common to both cases }
however, common steps can also be extracted into methods to avoid the if - else block:
} catch (NotAnInt e) { inCommon1(e); // handle NotAnInt inCommon2(e); } catch (ParseError e) { inCommon1(e); // handle ParseError inCommon2(e); } private void inCommon1(e) { // several steps // in common to // both cases } private void inCommon2(e) { // potentially several more // steps in common // to both cases }
source share