.net - C# try catch pattern help -
we need try catch in our code , becomes ugly like
public void foo() { try { dosomething(); } catch(exception e) { //do whatever e } } public int fooreturnint() { try { return intaftersomecalculation(); } catch(exception e) { //do whatever e foo() } }
imagine have huge class many public functions , have apply same try catch in every single function.
ideally, since try catch part identical, , can pass down func<> parameter helper function like
public void trycatch(func<something> thefunction) { try { thefunction(); } catch(exception e) { //processthe common exception } }
then i'd imagine tidy code alot, problem how write function? return type of function depended on return type of thefunction.
if really think needed, use:
public t trycatch<t>(func<t> thefunction) { try { return thefunction(); } catch(exception e) { // you'll need either rethrow here, or return default(t) etc } }
however, advise against it. sure need try/catch blocks in of these methods? there shouldn't many try/catch blocks unless catch wraps exception , rethrows... , that's rarer in c# in java, example.
you should catch exception when can either genuinely handle gracefully or need prevent process blowing because 1 request failed (for example). tend write few catch blocks - it's relatively rare can recover errors :)
this approach going lead harder time debugging, suspect. may still worth doing, should consider pros , cons first.
Comments
Post a Comment