33

The System.Exception class (actually any exception) has Data property which is almost always empty. While throwing exceptions, should this field be of any use? Or does it have some internal use that I am not aware of?

2
  • 1
    This is something that has always intrigued me. Why is there such a property? Isn't subclassing Exception a better way to include your own data? Apr 30, 2011 at 17:02
  • 1
    possible duplicate of Using Exception.Data
    – Cody Gray
    Apr 30, 2011 at 17:09

3 Answers 3

17

The documentation seems clear enough as to its use (emphasis added):

Gets a collection of key/value pairs that provide additional user-defined information about the exception.

Why does it exist in the first place? I assume it's the same reason Control has a Tag property. In the early days of .NET (before every Bob and Betty programmer understood objects and inheritance) they wanted to make the API simple enough that everyone could figure out how to add extra data to things.

However, the point of creating custom exceptions that derive from System.Exception is not necessarily to include additional information, but to make it possible for the client to limit the exceptions they catch to only those that they can handle. If they know how to handle a set of defined exceptions that your code can throw, they should be able to only catch those exceptions, without having to catch the base System.Exception class. What you should definitely never do is require the client code to catch a non-specific exception class and read a property to determine what type of exception it is (and thus whether or not they are able to handle it).

I've honestly never used this property before. I had to check the documentation to even see that it did indeed exist. But I imagine it's most useful for implementing custom exception logging. You can embed a lot of important information into the Data property (regardless of the level of derivation of exception class), and then pass that off to your logging code. Reflector indicates that it's used internally in a handful of places for precisely that purpose. It's also nice that all the information you provide here gets correctly serialized for you automatically.

3
  • I have a feeling that Control.Tag mostly exists due to designers (which Microsoft seems to be very fond of). As far as I know you need to jump through a few hoops to get your own subclassed TextBox to show up in a designer equally as nicely as the basic class. Exceptions are rarely designed using a GUI designer though. Apr 30, 2011 at 17:09
  • @Matti: I use custom controls all the time. I'm not aware of any such hoops. You have to add the controls to the toolbox, yes. But I'm not sure how that's any different from having to add a using declaration to use types defined in another namespace. (You can also rejigger the IDE to auto-populate the toolbox with controls defined in the same project.) The result is just as nice as the built-in controls, at least if you inherit from Control or one of its subclasses.
    – Cody Gray
    Apr 30, 2011 at 17:11
  • 2
    I use the Data property for tracking additional information about the error - usually state information for the method in which the error occurs, so that when I pass the error to higher level handlers, all that state information will be included in my logs. When tracking down bugs, that extra information in the logs is very useful.
    – Zarepheth
    Feb 19, 2014 at 15:41
16

Another note here, what I do when I inherit an exception and add properties, is to make the properties actually get and set from the data dictionary, and not from local variables.

[Serializable]
public class PacketParseException : Exception
{
    public byte[] ByteData
    {
        get
        {
            return (byte[])this.Data["ByteData"];
        }
    }

    public PacketParseException(string message, byte[] data, Exception inner) : base(message, inner)
    {
        this.Data.Add("ByteData", data);
    }
}

The way I see it, then the internal data is available from an Exception as well, for example when logging, so no need to cast to actual type.

9

With the new CallerMemberNameAttribute it's even easier to use the Data property for storage:

public class BetterException : Exception
{
    protected T GetValue<T>([CallerMemberNameAttribute] string propertyName = "")
    {
        return (T)Data[propertyName];
    }

    protected void SetValue<T>(T value, [CallerMemberNameAttribute] string propertyName = "")
    {
        Data[propertyName] = value;
    }
}

Usage:

class MyException : BetterException
{
    public MyException(string name)
    {
        Name = name;
    }

    public string Name
    {
        get { return GetValue<string>(); }
        set { SetValue(value); }
    }
}
3
  • 3
    This is a fantastic pattern. I'd go a step farther and add an overridden ToString to automatically include the Data properties.
    – James Haug
    Aug 3, 2016 at 17:15
  • Watch out for invalid casts in GetValue. The Data dictionary is public and mutable. Anyone who can get a reference to your exception can put a different data object behind one of those keys. .e.g. ex.Data["Name"] = 42; Mar 6, 2019 at 17:20
  • @StevenLiekens you're right and as a matter of fact I no longer use this. There are only two things that are useful about excepitons: the name of the exception and the message. You can forget the rest.
    – t3chb0t
    Mar 6, 2019 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.