CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
}
Console.ReadLine();
So, now that you understand the basic process of building a custom exception, you might wonder
when you are required to do so. Typically, you only need to create custom exceptions when the error is
tightly bound to the class issuing the error (for example, a custom file-centric class that throws a number
of file-related errors, a Car class that throws a number of car-related errors, a data access object that
throws errors regarding a particular database table, and so forth). In doing so, you provide the caller with
the ability to handle numerous exceptions on a descriptive error-by-error basis.
Building Custom Exceptions, Take Two
The current CarIsDeadException type has overridden the virtual System.Exception.Message property in
order to configure a custom error message, and has supplied two custom properties to account for
additional bits of data. In reality, however, you are not required to override the virtual Message property,
as you could simply pass the incoming message to the parent’s constructor as follows:
public class CarIsDeadException : ApplicationException
{
public DateTime ErrorTimeStamp { get; set; }
public string CauseOfError { get; set; }
public CarIsDeadException() { }
}
// Feed message to parent constructor.
public CarIsDeadException(string message, string cause, DateTime time)
:base(message)
{
CauseOfError = cause;
ErrorTimeStamp = time;
}
Notice that this time you have not defined a string variable to represent the message, and have not
overridden the Message property. Rather, you are simply passing the parameter to your base class
constructor. With this design, a custom exception class is little more than a uniquely named class
deriving from System.ApplicationException (with additional properties if appropriate), devoid of any
base class overrides.
Don’t be surprised if most (if not all) of your custom exception classes follow this simple pattern.
Many times, the role of a custom exception is not necessarily to provide additional functionality beyond
what is inherited from the base classes, but to supply a strongly named type that clearly identifies the
nature of the error, so the client can provide different handler-logic for different types of exceptions.
Building Custom Exceptions, Take Three
If you want to build a truly prim-and-proper custom exception class, you would want to make sure your
type adheres to .NET best practices. Specifically, this requires that your custom exception does the
following:
•
Derives from Exception/ApplicationException
•
Is marked with the [System.Serializable] attribute
269