java - How to improve ugly catch block using exception instanceof -
please pay attention: caller throws parentexception only!!
say aexception
, , bexception
inherit parentexception
.
in method af
, throws aexception
, bexception
, parentexception
.
void af() throws aexception, bexception, parentexception {}
the method caller
calls af
, throw parentexception
only.
void caller() throws parentexception
here lost information of subclasses of parentexception.
the method rootcaller
calls method caller
, rootcaller
can catch parentexception
thrown caller
, using 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 ugly , easy forget subclass of parentexception if subclasses many.
is there anyway improve such code?
current answer can not give me idea:
1, rootcaller cannnot use multi-catch simplify process cause caller throw parentexception.
2, because caller throw parentexception, there not other exception check if af changed latter throws more aexception , bexception, cexception.
as others have suggested in comments, should using multiple catch clauses.
void rootcaller() { try { caller(); } catch (aexception e) { // ... } catch (parentexception e) { // ... } catch (bexception e) { // ... } catch (anotherexception e) { // ... } catch (exception e) { // ... } }
the order of catches matters too. exception tested against each case in turn , trigger first 1 matches.
so example aexception
, bexception
extending parentexception
in above code catch (bexception e)
block can never reached catch (parentexception e)
reached , executed first.
Comments
Post a Comment