java - Handling an exception as a method argument -
java - Handling an exception as a method argument -
i looking design pattern handle exception
instances received method arguments.
to set context question, using gwt , have various asynchronous handlers come in form similar to:
public interface asynccallback<t> { void onfailure(throwable caught); void onsuccess(t result); }
so, onfailure
method receives throwable
instance need handle.
now, have number of exceptions can receive in method, example
constraintviolationexception
timeoutexception
nosuchelementexception
in handling code of course of study write following:
void handleexception(final exception e) { if(e instanceof timeoutexception) { handletimeout(); } else if (e instanceof nosuchelementexception) { handleinvalidelement(); } else { stopandcatchfire(); } }
but eye, looks ugly. big if..else if
chain combined heavy usage of instanceof
seems should avoided.
i thought maybe utilize try...catch
build handle exception
using following:
void handleexception(final exception e) { seek { throw e; } grab (timeoutexception te) { handletimeout(); } grab (nosuchelementexception nsee) { handleinvalidelement(); } grab (exception ex) { stopandcatchfire(); } }
but seems abuse somehow. see downsides sec approach or approach go avoid first case?
could not have dictionary of exceptionhandlers keyed type of exception handle, when exception in dictionary handler exception type. if there one, pass exception handler, if there isn't utilize default handler.
so handler becomes this:
void handleexception(final exception e) { if (handlers.containskey(e.gettype()) { handlers[e.gettype()].handle(e); } else { defaulthandler.handle(e); } }
my java bit rusty, illustration c-sharpy should simple plenty translate (though remembered not capitalise first letter of :))
this approach should have advantage can add together new handlers simply.
it suffer if have same handler sub types, have register each subtype explicitly.
to around issue create each handler responsible making decision whether can handle exception:
public interface exceptionhandler { bool canhandle(exception e); void handle(exception e) }
then set handlers in list iterate asking each 1 if can handle current exception , when find 1 can, handle it.
java design-patterns exception-handling
Comments
Post a Comment