7.3. The Simplest Possible Example

To illustrate the usefulness of structured exception handling, we need to create a class that will throw an exception under the correct (or one might say exceptional) circumstances. Assume we have created a new C# Console Application project (named SimpleException) that defines two class types (Car and Radio) associated by the "has-a" relationship. The Radio type defines a single method that turns the radio's power on or off:

class Radio
{
  public void TurnOn(bool on)
  {
    if(on)
      Console.WriteLine("Jamming...");
    else
      Console.WriteLine("Quiet time...");
  }
}

In addition to leveraging the Radio class via containment/delegation, the Car class (shown below) is defined in such a way that if the user accelerates a Car ...

Get Pro C# 2010 and the .NET 4 Platform, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.