开发者

Eliminating repetitive try/catch code

开发者 https://www.devze.com 2023-03-20 21:33 出处:网络
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

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;
       }
    }
 }


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.


It does sound like you're looking for functionality that AOP can provide. Depending on what you're specifically going for, you might be able to get a lot of the same benefits without the extra overhead simply by writing some helper methods, the way Peter O. suggests.

I personally don't find that I have a lot of repetitive exception handling code due to the fact that Exceptions are... well... exceptional. They shouldn't be part of the normal code flow, and unless there's something very specific that needs to be done in response to a specific type of Exception, the best policy is generally not to catch them at all, at least until they trickle up to a high level where you want to log them.

0

精彩评论

暂无评论...
验证码 换一张
取 消