Please pay attention: caller throws parentexception only!!
Say that aexception
, and bexception
inherit from parentexception
.
In method af
, it throws aexception
, bexception
and parentexception
.
void af() throws aexception, bexception, parentexception {}
The method caller
calls af
and throw parentexception
only.
void caller() throws parentexception
Here we lost the information of subclasses of parentexception.
The method rootCaller
calls the method caller
and rootcaller
can only catch parentexception
thrown by caller
and using the following exception process catch block:
void rootCaller() {
try {
caller();
} catch(parentexception e) {
if(e instanceof aexception) {
......
} else if(e instanceof bexception) {
......
} else if(e instanceof parentexception) {
......
} else {
......
}
}
This is so ugly and very easy to forget some subclass of parentexception if the subclasses are too many.
Is there anyway to improve such code?
Current answer can not give me any idea:
1, rootCaller cannnot use multi-catch to simplify the process cause caller only throw parentexception.
2, because caller only throw parentexception, there is not any other exception check if the af is changed latter to throws more than aexception and bexception, say cexception.
As others have suggested in the comments, you should be using multiple catch clauses.
The order of the catches matters too. The Exception will be tested against each case in turn and only trigger the first one that matches.
So for example with
AException
andBException
extendingParentException
in my above code thecatch (BException e)
block can never be reached ascatch (ParentException e)
is reached and executed first.