If you can, always use separate catch
blocks for individual exception types, there's no excuse to do otherwise:
} catch (NotAnInt e) {
// handling for NotAnInt
} catch (ParseError e) {
// handling for ParseError
}
...unless you need to share some steps in common and want to avoid additional methods for reasons of conciseness:
} catch (NotAnInt | ParseError e) {
// a step or two in common to both cases
if (e instanceof NotAnInt) {
// handling for NotAnInt
} else {
// handling for ParseError
}
// potentially another step or two in common to both cases
}
however the steps in common could also be extracted to methods to avoid that if
-else
block:
} catch (NotAnInt e) {
inCommon1(e);
// handling for NotAnInt
inCommon2(e);
} catch (ParseError e) {
inCommon1(e);
// handling for ParseError
inCommon2(e);
}
private void inCommon1(e) {
// several steps
// common to
// both cases
}
private void inCommon2(e) {
// several steps
// common to
// both cases
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…