tags:

views:

45

answers:

1

I have been developing pages and web parts in SharePoint 2007/2010 for the past year. One of the things that I always incorporate in my code is try/catch blocks to deal with error handling if an exception is thrown. That way, if I have a web part that breaks, I show a nice error message to the user in that specific web part, rather than at the top of the page or a full page error. I am fine with this process, but I am looking for some input on my approach of using try/catch blocks (as I understand that there can be performance implications).

In general, I always use try/catch blocks when conducting DB or web service calls. I will even sometimes wrap my generic C# code in try/catch blocks if there is complicated logic that is implemented (and I haven't been able to test all the different cases). Sometimes, I just have a little paranoia going on and will wrap all the code in an entire web part with a try/catch.

Can I please get some feedback on the use of try/catch blocks for general C# development, and specifically with C# development in the SharePoint world? Additionally, I would love to understand how to effectively embed try/catches in my C# code while developing SharePoint solutions (is there a more global way of doing this?)

Thanks in advance.

+1  A: 

With error handling in the SharePoint world, you're usually going to be focused on performance. If you're worried about performance, you'll want to let exceptions bubble up whenever possible. I usually wrap "entrance" methods with try/catch blocks. For example, event handlers in asp.net forms, web parts, user controls, etc. Then I'll wrap code in utilities, data access, etc. when I want to throw custom exception types, customize the error message, etc.

Unfortunately, I haven't found a global way to handle errors in SharePoint. I have done a HandleError utility method for web parts that I pass in 'this' and the exception object. (WSPBuilder Extensions web part item actually has a good implementation of this built in.) The try/catch blocks themselves are still local to the web part event handlers though.

knight0323
We do mostly this as well. Our big thing is a Try/catch in the CreateChildControls to catch most errors.
Kit Menke