Writing code which has to handle the same exceptions time and time again constantly gets boring.
Is there a way to write code, without try/catch, and add attributes to the method to catch (and handle) the various exceptions which may occur? This sounds like AOP (Postsharp), would this be the ideal solution?
So I want to write classes which can dictate where/how an exception is logged, rethrown, etc, and they derive from attributes and any base class/interface. And then re-use these and apply them to different methods throughout the code. This will greatly improve consistency.
Thanks
What I would suggest is write methods that take delegates (such as Func and Action) as arguments. The delegates would represent the "try" block. The individual methods would handle exceptions that occur within the delegates in different ways.
Example:
OverflowHandler(delegate(){ checked{ x+=200; } });
where the OverflowHandler method would handle the OverflowException and would probably log and rethrow other exceptions.
Here is an example of how the OverflowHandler method could look:
public void OverflowHandler(Action func){
try {
func(); // call the delegate
} catch(Exception e){
if(e is OverflowException){
// handle the overflow exception
} else {
// log exception and rethrow
LogException(e);
throw;
}
}
}
What I would suggest is write methods that take delegates (such as Func and Action) as arguments. The delegates would represent the "try" block. The individual methods would handle exceptions that occur within the delegates in different ways.
Example:
OverflowHandler(delegate(){ checked{ x+=200; } });
where the OverflowHandler method would handle the OverflowException and would probably log and rethrow other exceptions.
Here is an example of how the OverflowHandler method could look:
public void OverflowHandler(Action func){
try {
func(); // call the delegate
} catch(Exception e){
if(e is OverflowException){
// handle the overflow exception
} else {
// log exception and rethrow
LogException(e);
throw;
}
}
}
Here's something from the MS Practices and Patterns team.
Introduction to the Exception Handling Application Block http://msdn.microsoft.com/en-us/library/ff664698(v=PandP.50).aspx
definitely they've got the concept of rethrow + various policies in there.
Do I recommend it? Not sure. I looked at their implementation and ended up using some of their concepts. I told myself I'd come back to it, but I haven't had a chance yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With