Featured post
c# - Problem with too many try catch -
is possible write method outtype? trydo(func, out exception, params)
call func(arg1,arg2,arg3,...)
params contains arg1,arg2,arg3,...
, return func return value , if exception occurred return null , set exception?
can done better function signature?
for example have string foo1(int i) { return i.tostring()}
void foo2(int[] a) {throw new exception();}
and call
string t = trydo(foo1, out ex, {i});
trydo(foo2, out ex, {});
-----------edited------------------
string t; someclass c; try { t = foo1(4, 2, new otherclass()); } catch (exception ex) { log(ex); if (/*ex has features*/) throw ex; } try { foo2(); } catch (exception ex) { log(ex); if (/*ex has features*/) throw ex; } . . .
i want make this.
string t = trydo(foo1, out ex, {4, 2, new otherclass()); examine(ex); someclass c = trydo(foo2, out ex, {}); examine(ex);
i avoid using out
parameters unless absolutely necessary.
here quote design guidelines developing framework libraries:
avoid using out or reference parameters.
working members define out or reference parameters requires developer understand pointers, subtle differences between value types , reference types, , initialization differences between out , reference parameters.
you can instead create return type wraps result of call:
class callresult<t> t : class { public callresult(t result) { result = result; } public callresult(exception exception) { exception = exception; } public t result { get; private set; } public exception exception { get; private set; } public boolean issuccessful { { return exception == null; } } }
your method implemented this:
callresult<t> trydo<t>(func<object[], t> action, params object[] args) t : class { try { return new callresult<t>(action(args)); } catch (exception ex) { return new callresult<t>(ex); } }
you can call this:
var callresult = trydo<string>(foo1, 4, 2, new otherclass()); if (!callresult.issuccessful) examine(callresult.exception);
however, if intend rethrow exception in examine
method loosing stacktrace you should reconsider approach.
- Get link
- X
- Other Apps
Comments
Post a Comment