Free mag vol1 | Page 320

CHAPTER 7  UNDERSTANDING STRUCTURED EXCEPTION HANDLING // Is the car still operational? private bool carIsDead; // A car has-a radio. private Radio theMusicBox = new Radio(); // Constructors. public Car() {} public Car(string name, int speed) { CurrentSpeed = speed; PetName = name; } public void CrankTunes(bool state) { // Delegate request to inner object. theMusicBox.TurnOn(state); } // See if Car has overheated. public void Accelerate(int delta) { if (carIsDead) Console.WriteLine("{0} is out of order...", PetName); else { CurrentSpeed += delta; if (CurrentSpeed > MaxSpeed) { Console.WriteLine("{0} has overheated!", PetName); CurrentSpeed = 0; carIsDead = true; } else Console.WriteLine("=> CurrentSpeed = {0}", CurrentSpeed); } } } Now, if we implement a Main() method that forces a Car object to exceed the predefined maximum speed (set to 100, in the Car class) as shown here: static void Main(string[] args) { Console.WriteLine("***** Simple Exception Example *****"); Console.WriteLine("=> Creating a car and stepping on it!"); Car myCar = new Car("Zippy", 20); myCar.CrankTunes(true); for (int i = 0; i < 10; i++) myCar.Accelerate(10); 258