Pages

Tuesday, July 17, 2012

Managing Exceptions Using Delegates

Now that you have perfect code that follows Microsoft's Exception Management Practices for SharePoint ;) you may be wondering..."Is there a way I can get rid of all the *extra* try / catch / finally blocks?" Well this post is to help provide an option that I recently implemented (as a side note if you have other options please feel free to comment below).

Don't let this example steer you toward catching general exceptions as the norm. This example is mainly to help provide some guidance on abstracting exception handling but not at the risk of generalizing exception management.

-The first step is to become familiar with Delegates in C# (if you are not already familiar). 

-Next you will need to create a class with at least two methods that will serve as the Exception Manager. Each method will receive a Delegate, as a parameter, that points to the Routine that is being wrapped. The first method will only handle exceptions for Actions (nothing is returned by the Routine). The second method will handle exceptions for Functions (something is returned by the Routine)

-Finally you will need to wrap a Routine call using a Delegate pointer to that routine and pass it to either method in the Exception Manager class.

You can see the result in the following example. You can also download a code sample from my SkyDrive.

Before:
 try  
 {  
  DoSomething();  
 }  
 catch(Exception ex)  
 {  
  //Handle Exception  
 }  
 finally  
 {  
 //Continue...  
 }  

After:
 ExceptionManager.ProcessFunc(() => DoSomething());  

2 comments :

  1. Oh my goodness! an amazing article dude. Thank you However I am experiencing issue with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anyone who knows kindly respond. Thnkx

    ReplyDelete
    Replies
    1. Hey Steve, thanks for the feedback. I just tested the RSS from the 'Subscribe To' menu on the right column and everything is working on my end :\ . Feel free to ping me via Google+ and I can try to help.

      Delete

I always welcome constructive feedback. Thanks.