1: using(SPSite site = new Site(http://www.portal.com)) 2: { 3: SPWeb web = site.OpenWeb("/anotherWeb/"); // no exception 4: 5: string title = web.Title; // throws exception 6: }
The first line in the using clause will not throw an exception even if anotherWeb doesn’t exist , but you’ll encounter a FileNotFoundException exception in the second line since web is a null reference.
To make your code more robust, you should check the existence of the web before using it as follows:
1: using(SPWeb web = site.OpenWeb("/anotherWeb/")) 2: { 3: if(web.Exists) 4: { 5: string title = web.Title; 6: } 7: }
Alternatively, The SPSite.OpenWeb method has a (string, bool) overload. If you set the bool to true you should get an exception if the site doesn’t exist. Waldek Mastykarz has explained this behavior on his blog @http://blog.mastykarz.nl/inconvenient-opening-spsite-openweb.