The SLAR on ArgumentNullException

To continue sharing some of the color found in the .NET Framework Standard Library Annotated Reference Vol 1, here is some information from the ArgumentNullException class.

   public class ArgumentNullException : ArgumentException

   {

       // Constructors

       public ArgumentNullException ();

       public ArgumentNullException (string paramName);

       public ArgumentNullException (string paramName, string message);

   MS CF protected ArgumentNullException (SerializationInfo info, StreamingContext context);

   }

BA This class goes down in the API design hall of shame. ArgumentNullException does not follow the exception constructor pattern given in the Design Guidelines Specification, which says the constructor overloads should include at least:

       public XxxException ();

       public XxxException (string message);

       public XxxException (string message, Exception inner);

The rationale for violating this guideline was that the parameter name would be much more commonly specified than the message text. However, because nearly every other exception in the system does follow the pattern, the usual result is that the force

of habit wins out. Developers commonly make this mistake:

throw new ArgumentNullException (“must pass an employee name”);

Rather than:

throw new ArgumentNullException (“Name”, “must pass an employee name”);

This mistake means that we end up with an error message such as this one:

Unhandled Exception: System.ArgumentNullException: Value cannot be null.

Parameter name: “must pass employee name”

Lesson learned: Just follow the pattern.

JR In addition to Brad’s comments, a properly designed exception class should

also allow for serializability. Specifically, this means that the class should have the

System.SerializableAttribute applied to it and the class should implement

the ISerializable interface with its GetObjectData method and special constructor.

These two methods should serialize/deserialize any fields in the class and be sure to

call the base class methods so that any fields in the base class are also serialized/

deserialized. If the exception class is sealed, the constructor can be marked private;

otherwise, mark the constructor as protected. Since GetObjectData is an interface

method, mark it as public.

 ----

 

Amazon Rank: 30,643 up from 1,026 right after my last post... Maybe this post have the same effect ;-)