Thursday, May 28, 2009

Exception handling Base WebPart

This piece of code will revolutionise the way you develop web parts in sharepoint. No more pages crapping out on you, no more crashes or unsolvable problems. All exception handling done for you automatically without the need to include a single try/catch block. I'm not saying you should not handle exceptions which you can forsee. But those are the easy ones. What about those unexpected ones?
Andreas Knudsen, a fellow SharePoint Programmer came up with a beautiful solution which takes full advantage of a combination between early and late binding to force the runtime to execute the exception handling version of the base routines before execuing your implementation code. As I'm not even going to try to take credit for this gem, get the code directly from the genius himself

http://andreascode.blogspot.com/2007/12/general-exception-handling-in-web-parts.html

How does it work? Playing with polymorphism is the answer.
The runtime always tries to find out the best version of a method on an object to call, no matter what type the pointer is.
When you put a line of code like

MyWebPart.CreateChildControls()

into your own code, the runtime will not have to look far, as you're calling it on the type of which the object is. But...

WebPart x = MyWebPart;
x.CreateChildControls();

Now the runtime will need to start at the base class WebPart and figure out which version is the best to call. Normally each new version overrides the old one and the runtime will end up at MyWebPart.CreateChildControls(). Unless you put a stop sign in between. Such a stop sign is the new keyword. When you have a class in between WebPart and MyWebPart (like MyBaseWebPart) and instead of writing public override CreateChildControls() but public new CreateChildControls() the runtime is forced to take a step back and execute the one a level up. To make it more visible you can seal off the exception handling method, just to be sure nobody tries to override it.

So now we've forced the runtime to execute the version of code that has exception handling. How do we get back to our implementation code? Through sidestepping the Stop sign. You need a new class which inherits from the exception handling class for this. the exception handling one calls a new function like CreateChildControlsX and the runtime will again try to figure out the best version and will end up in derived.CreateChildControlsX because you overrode it there. Here you simply call the original function name again (CreateChildControls) and the runtime will find the best version again. Now the runtime is not starting at the top (WebPart) but at the current location (derived) and thus the Stop sign is left behind and it can go all the way down to your implementation and execute that.

I know it sounds so geeky, But thise piece of code is seriously cooooooool.

No comments: