Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have been developing pages and web parts in SharePoint 2007/2010 for the past year. One of the things that I always incorporate in my code is try/catch blocks to deal with error handling if an exception is thrown. That way, if I have a web part that breaks, I show a nice error message to the user in that specific web part, rather than at the top of the page or a full page error. I am fine with this process, but I am looking for some input on my approach of using try/catch blocks (as I understand that there can be performance implications).

In general, I always use try/catch blocks when conducting DB or web service calls. I will even sometimes wrap my generic C# code in try/catch blocks if there is complicated logic that is implemented (and I haven't been able to test all the different cases). Sometimes, I just have a little paranoia going on and will wrap all the code in an entire web part with a try/catch.

Can I please get some feedback on the use of try/catch blocks for general C# development, and specifically with C# development in the SharePoint world? Additionally, I would love to understand how to effectively embed try/catches in my C# code while developing SharePoint solutions (is there a more global way of doing this?)

Thanks in advance.

share|improve this question
add comment

6 Answers

up vote 6 down vote accepted

I always wrap all webpart execution in a try catch and output the error. One thing I hate the most is visiting a page with 5 webparts and one of them is faulty and the whole page blows up with the "Unexpected error has occurred". I then don't know which one to investigate or close. So in my custom baseclass, I provide three types of messages that the webpart can output: Notices, Errors, and Debug. In the webpart properties one can decide whether to display these messages or not. I also have these messages tied into enterprise library so with a simple config change, I can having notices, errors, or debug info from all the webparts outputted to a trace file, or send me an email, etc. I then output these messages on render in the baseclass.

Notices are such things like "Please assign this webpart a list", etc.

Errors are messages that are caught in the try catch block

Debug shows some other helpful information as well as webpart execution time or a full stack trace of the error.

I like following this route because then in my code I am not afraid of throwing my own exceptions when something bad happens. As far as performance goes, I can't really notice. Most of my webparts render sub-second and a lot are rendering in less than a tenth of a second.

On another note, I've also implemented a httpmodule to catch all errors and send me an e-mail on any error that happens in sharepoint. Yes, you get a lot of "The specified name is already in use" and other such pointless e-mails, but it does let me know when something bad has happened or to catch a faulty webpart where it is hard to reproduce the issue.

share|improve this answer
add comment

I tend to encapsulate only the logic that will throw an exception inside a try-catch as possible, rather than squeezing in the entire logic of a method into the catch block with the catch handling "any" exceptions in the trailing end of the method. I'm not sure what benefits this truly brings but for me this is just out of habit.

As for handling of exceptions I think the Patterns and Practices group have advice on how to render errors in webparts, and you could also use System.Trace.Write for writing debug data to the trace log for monitoring.

share|improve this answer
add comment

Steve and James both offer good advice -- and it seems like your approach is sound too. We typically do the same thing -- specific catches where possible and generic catches around the whole thing. The one thing that I would add is that in large environments where the applications group hands off support of the system to the operations or help desk team after implementation, sometimes it makes good sense to send the non-end-user messages to the Windows application log instead of to a tracefile or email. That way the support team can look at things centralized in the event viewer rather than having to learn another location to look for errors. It doesn't make sense in every situation, but it helps immensely in others.

share|improve this answer
    
Good call on the thinking of helpdesk teams - write errors & warnings to somewhere they're used to looking. –  James Love Jul 30 '10 at 22:31
add comment

You specify that you "handle" the error, but dont go into specifics in what implies. Also you dont specify what errors you catch or where you catch them.

When you swallow errors, you must make sure that the error dont go unnoticed. Here im not talking about the end user -its a good solution to trap the errors, and secure the user a good experience, its just not enough: you need to log the error either in the trace/ULS log, event log or some custom log so that the ones that monitor your solution can see that something went bad and act upon it. There are several logging mechanisms out there (the one included in Sharepoint Guidance is good and supports re-plugging with something else without changing too much code due to its decoupled design). In SharePoint 2010 you also have the possibility to add a correlation ID for your custom code, and custom logging/monitoring through SPDiagnosticsService and SPMonitoredScope.

Also where and what you catch is important. You shouldnt blindly catch all (System.Exception) exceptions but instead know what exceptions could happen in a given situation (know your API) and handle those that makes sense and let SharePoints own error handling take care of the rest. Again this depends on the severity of the error and how critical the application is. If its a weather web part, the user would probably rather be presented with a small error inside the web part, that something went wrong, but if its a business critical application, its our responsibility to make the user aware that the application failed.

You mention performance, and its true that there is a small performance penalty involved when doing try/catch blocks, but as long as you dont nest them (boy have i seen that, i think the record is 7 nested try catches!) and dont blindly swallow errors without doing anything:

try
{
   // normal logic
}
catch // this is bad!
{}

If you do choose to swallow errors and show an error message, be sure to log it, and be sure that you do so all the places that the code could fail (basicly all public overridden methods). If you have private methods where you catch exceptions, rethrow them and let the general exception handling catch them. Here its important to not to specify a variable, or the error will be cast as such an error :

try
{
  // normal logic
}
catch (ArgumentException ex) // dont specify ex!
{
  throw; // this could also be an ArgumentNullException or ArgumentOutOfRangeException, but since you specified ex it is cast to ArgumentException

Finally you shouldnt use exception handling to control your program flow:

// this is bad
try
{
   SPList list = web.GetList(listUrl);
}
catch ( FileNotFoundException )
{
   //create list
}

If the topic interests you, I can recommend Wictor Wilén's new book on SharePoint 2010 Web Part development: SharePoint WebParts in Action. Chapter 8 covers the topic of troubleshooting web parts in detail.

share|improve this answer
add comment

Most of the time when creating webparts or features I'll create a try-catch block in the main method, so every exception is catched. Just to be safe. Reason is like most others here write, your web page still runs, even though your webpart crashes. When I know a specific error can arise, I'm using a more specific exception on the place where it's most usefull. It's best to write a small errorhandler framework for such things, just like in regular .NET development. Perhaps these links are a nice read: http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx http://www.c-sharpcorner.com/UploadFile/akrao/ExceptionManagement11142005020738AM/ExceptionManagement.aspx http://msdn.microsoft.com/en-us/library/seyhszts.aspx

I discovered a neat method which lets you write in the Sharepoint logs. I'm using this method to log my errors in the code.

Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception Occurred in this method : {0} || {1}", ex.Message, ex.StackTrace);

Also, I'm thinking of adding serious bugs in the Windows event logger. That way a system engineer will see errors/warnings when doing some maintenance. They'll be able to contact the developer directly in a lot of cases.

share|improve this answer
add comment

Here is a great solution for catching all exceptions and preventing pages from crashing using a base web part class:

http://andreascode.blogspot.com/2007/12/general-exception-handling-in-web-parts.html

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.