Getting levels of the SharePoint Heirarchy and their Exceptions

Something that I have to do time and again is get some element of SharePoint’s heirarchy, such as a site collection, site, list or item. This is pretty typical – that’s why we all use USING to ensure proper disposal of SPSites and SPWebs, right? But what happens if the thing you’re after isn’t there? What exception get’s thrown? Well, this should be pretty clear:

try
{
    //FileNotFoundException if doesn't exist
    using (SPSite site = new SPSite(siteGuid))
    {
        //FileNotFoundException if doesn't exist
        using (SPWeb web = site.OpenWeb(webGuid))
        {
            //SPException if doesn't exist
            SPList list = web.Lists[listGuid];

            //ArgumentException if doesn't exist
            SPListItem item = list.GetItemByUniqueId(itemGuid);
        }
    }
}
catch (System.IO.FileNotFoundException fileEx2)
{
    // Site or Site Collection Not Found
}
catch (SPException spEx2)
{
    // List not found
}
catch (ArgumentException argEx2)
{
    // Item not found
}

Hopefully that might prove useful to someone – and a good reminder for me.

Advertisements
Getting levels of the SharePoint Heirarchy and their Exceptions

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s