I have this code:
try {
do_stuff();
return do_more_stuff();
} catch (UnsupportedEncodingException e) {
throw CustomException.programmer_error(e);
} catch (ProtocolException e) {
throw CustomException.programmer_error(e);
} catch (MalformedURLException e) {
throw CustomException.programmer_error(e);
} catch (SocketTimeoutException e) {
throw new CustomException(e);
} catch (IOException e) {
throw CustomException.unexpected_error(e);
}
I now need to have all those catch blocks in another similar function. What is the best way to avoid duplication here?
Note that the code inside the two try blocks is not very similar.
Also I can’t really put the set of catches higher up.
Note, I’d prefer to avoid:
try {
do_stuff();
return do_more_stuff();
} catch (Exception e) {
handle_exception_via_rtti(e);
}
Personally I’d try to make the
part conform to a more general format in order to apply Strategy (as a pattern).
Then you can refactor all the places where you call this kind of block so that they can call a more generalized block (where the catches are laid out just once).