C# – Whats the best way to handle errors in code

cerror handling

So I'm a little concerned about my error handling… Currently my execution path looks something like this:

Users.aspx -> App_Code/User.cs -> Data Layer/User.cs

So now when I try to update a user record, I put my Try/Catch block in the event handler and ensure that only the App_Code class interacts with the data layer. Exceptions that happen on the data layer, to my understanding, should bubble up to the event handler below.

In the data layer, I started off with this:

public void Update()
{
    var product = (from p in db.products
                        where p.productid == id
                        select p).FirstOrDefault();

    if (product != null)
    {
        // update the thing
    }
}

More info on reddit.

After chatting with a friend, he recommended something like this:

public void Update()
{
    int count = db.users.Count(u => u.userid == id);

    if (count == 0) // no user found
    {
        throw new ValidationException(String.Format("User not found for id {0}.", id));
    }
    if (count > 1) // multiple users
    {
        throw new ValidationException(String.Format("Multiple users found for id {0}.", id));
    }

    var user = db.users.FirstOrDefault(u => u.userid == id);
    // update the user record
}

Then I went onto IRC where they suggested I create my own Exceptions.

I can see the pros here, but it seems a bit unnecessary when my friend's option will work just fine.

Basically I'm just really confused as to how I should handle this… Obviously my initial option is insufficient, but it seems like creating my own exceptions might be complicating things too much.

So what should I do here?

Best Answer

The point of writing custom exceptions is that you intend to do something useful with them.

Is showing them to the user "useful"?
Probably not. They look scary.

Is logging them to a file for later examination "useful"?
Possibly, especially if the application is about to keel over and die because you're doing this in a "global" exception handler (which is about all they're good for).

Is catching a particular Type of exception and handling it (i.e. writing code to deal with the problem as it happens and to correct that problem, preferably without the user knowing anything about it) "useful"?
Oh yes!

Why use custom Exception Types? Because that's how most languages expect to identify exceptions. Look at "catch" clauses - they look for specific Types of Exception. Sorry to say it but I would vehemently disagree with your friend's recommendation - throwing the same [class of] ValidationException [objects] all over the place but relying on the Text property to explain what's going on. That's only useful in one scenario - where you show Exceptions directly to the user and that's a pretty poor practice, in my book anyway.

Related Topic