Share via


Don’t Throw Errors…Even in SharePoint

 

So, as all good .NET coders know, it’s generally considered bad practice to use an Error as part of your code logic. For instance, I recently came across a client’s SharePoint code that was trying to test for the existence of a file in a specific web (i.e. a website.) It looked like this:

SPFolder myFolder = newlist.RootFolder;

try
{
myFolder.Files["MySPPage.aspx"].Delete();
}
catch { ;} //the form doesn't exist yet

myFolder.Files.Add("MySPPage.aspx", …blah, blah, blah

As is, the code above will throw an error if the file we want doesn’t exist. As all good .NET coders know, throwing errors in .NET code is one of the most expensive actions (in terms of processing time) one can undertake. So it’s always best practice to only throw errors if it’s really a case of an error occurring. It is not a good idea to throw an error simply to test for the existence of a file.

Now, sometimes whomever created the underlying objects didn’t provide any other way to accomplish a simple check like this. In this case, however, that is not so. The above code can be re-factored like this:

using (SPSite site = new SPSite("https://server/site"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("/site/lib/folder/MySPPage.aspx");
if (file.Exists)
{
...
}
}
}

(This example taken from the StackOverflow.com forums. Many thanks to Lars Fastrup for his answer.)

Or, if you really need to use an SPFolder object obtained by getting newlist.RootFolder, you can do that and simply supply the value of SPFolder.ServerRelativeUrl—along with the filename—to the GetFile() method. Much better. Now we aren’t spending processing cycles generating an error we’re just going to ignore anyway!

By the way (and to be clear), yes, the SPFile object will not be null after the call to web.GetFile(). If that were the case, calling file.Exists() would result in an error. If MySPPage.aspx doesn’t exist, SPFile simply won’t be able to be manipulated as if it were referring to an actual file. And file.Exists will return false.

Technorati Tags: SharePoint Development,Development,SharePoint 2007,SharePoint 2010