Free mag vol1 | Page 330

CHAPTER 7  UNDERSTANDING STRUCTURED EXCEPTION HANDLING } messageDetails = message; CauseOfError = cause; ErrorTimeStamp = time; // Override the Exception.Message property. public override string Message { get { return string.Format("Car Error Message: {0}", messageDetails); } } } Here, the CarIsDeadException class maintains a private field (messageDetails) that represents data regarding the current exception, which can be set using a custom constructor. Throwing this exception from the Accelerate() method is straightforward. Simply allocate, configure, and throw a CarIsDeadException type rather than a System.Exception (notice that in this case, we no longer need to fill the data collection manually): // Throw the custom CarIsDeadException. public void Accelerate(int delta) { ... CarIsDeadException ex = new CarIsDeadException (string.Format("{0} has overheated!", PetName), "You have a lead foot", DateTime.Now); ex.HelpLink = "http://www.CarsRUs.com"; throw ex; ... } To catch this incoming exception, your catch scope can now be updated to catch a specific CarIsDeadException type (however, given that CarIsDeadException “is-a” System.Exception, it is still permissible to catch a System.Exception as well): static void Main(string[] args) { Console.WriteLine("***** Fun with Custom Exceptions *****\n"); Car myCar = new Car("Rusty", 90); try { // Trip exception. myCar.Accelerate(50); } catch (CarIsDeadException e) { Console.WriteLine(e.Message); Console.WriteLine(e.ErrorTimeStamp); Console.WriteLine(e.CauseOfError); } 268