Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exceptions

This is my first application that will deal with exceptions properly. It's a WCF service. All the other before were simple apps just for myself. I have very small knowledge about exception handling in C#.

I have a code like this:

MembershipUser memUser = Membership.GetUser(username);

DatabaseDataContext context = new DatabaseDataContext();
UserMembership user = UserMembership.getUserMembership(memUser);
ItemsForUser itemUser = Helper.createItemForUser(ref item, memUser);
Helper.setItemCreationInfo(ref item, user);
context.Items.InsertOnSubmit(item);
context.SubmitChanges();

In this code a few exceptions can happen. Like NullReferenceException for example. How do I know which object caused the exception so I can know what to do in the catch and what to return to the client?

like image 400
Mité Avatar asked Mar 02 '12 00:03

Mité


1 Answers

In general, you should not catch any exceptions.

I know this sounds strange, but the fact is that you should only catch exceptions you can actually do something about, and you usually can't do anything about exceptions.

The "exceptions" to this rule have to do with what it means to "handle" an exception. In some applications, "handling" the exception means to log it. In others (ASP.NET, for instance), it's better to not handle the exception, because the framework (ASP.NET Health Monitoring in this case) will log it for you.

In event-driven code, like Windows Forms, I find it's necessary to catch exceptions within event handlers. At least in earlier versions of .NET, allowing the exception to propagate outside of, for instance, a button click event produced unpleasant results. I typically catch the exception and display it in a dialog box.

In a multi-tier application, one might catch exceptions on tier boundaries, then rethrow a new, tier-specific exception:

try
{
   // ...
}
catch (Exception ex)
{
    throw new TierException("Some message", ex);
}

Another use case is to catch the exception, then throw a new exception with more information in it:

public int GetValueFromConfigurationFile(...)
{
    const string configFileName = "...";
    try
    {
        // ...
    }
    catch (FileNotFoundException fEx)
    {
        throw new InvalidOperationException(
            String.Format("Can't find configuration file {0}", configFileName), 
            fEx);
    }
}

In this case, you are catching a specific exception (FileNotFoundException), and providing your caller information they could not otherwise know: that the file not found was a configuration file.

The general message is: - Only catch exceptions you know how to handle - Catch the most specific exception possible - Always include the inner exception when creating a new exception, to preserve the chain of exceptions - To rethrow the current exception, use throw;, not throw ex;

There are a few more, and I'll try to find you the reference from the Microsoft Framework Design Guidelines.

P.S. If someone can find the question this is a duplicate of, feel free to close as a duplicate. I don't mind losing any rep from this. I just couldn't find the duplicate.


I should have just posted the link to the "exception-handling" tag wiki, where it says:

However, for exception handling in the context of .NET programs, see "Design Guidelines for Exceptions".

like image 149
John Saunders Avatar answered Sep 19 '22 21:09

John Saunders