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.