Posted by: R Manimaran | February 15, 2011

SharePoint Object Model Exceptions: Don’t use General Exception

SharePoint Object Model Exceptions: Don’t use General Exception

While using Object model to access the SharePoint Sites most of the time we used to use the general Exception in our code. It is not the best practice to catch general exception. Catching Exception may impact the performance. Always try to use the specific exception.

Here are the some common exceptions we can use while using object model.

SPSite: use FileNotFoundException

SPWeb: use FileNotFoundException and SPException

If the Specified web is not found it will through FileNotFoundException. Apart from that SPWeb.OpenWeb() method has a method named ValidateWebName which do a validation of the specified Url.

So while providing webName ensure the following

· Don’t use any illegal characters in the webUrl

· Don’t use leading or trialing slash(/)

· Don’t use Reserved WebName

SPList: Use ArgumentException

While using SPListCollection, if the specified list is not found in the collection then it will throw Argument Exception.

SPListItem: Use ArgumentException

While accessing a Specific list item it will throw Argument Exception if the corresponding item is not found.

From the above your object model code can be well written as

using (SPSite site = new SPSite(siteUrl))
using (SPWeb web = site.OpenWeb("MyWeb"))
SPList myList = web.Lists["SampleList"];
SPListItem item = myList.GetItemById(2);
catch (FileNotFoundException fileEx)
catch (SPException spEX)
catch (ArgumentException argEx)
Console.WriteLine("Argument Exception:"+argEx.Message);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: