CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
}
Console.ReadLine();
we would see the following output:
***** Simple Exception Example *****
=> Creating a car and stepping on it!
Jamming...
=> CurrentSpeed = 30
=> CurrentSpeed = 40
=> CurrentSpeed = 50
=> CurrentSpeed = 60
=> CurrentSpeed = 70
=> CurrentSpeed = 80
=> CurrentSpeed = 90
=> CurrentSpeed = 100
Zippy has overheated!
Zippy is out of order...
Throwing a General Exception
Now that we have a functional Car class, I’ll demonstrate the simplest way to throw an exception. The
current implementation of Accelerate() simply displays an error message if the caller attempts to speed
up the Car beyond its upper limit.
To retrofit this method to throw an exception if the user attempts to speed up the automobile after it
has met its maker, you want to create and configure a new instance of the System.Exception class,
setting the value of the read-only Message property via the class constructor. When you want to send the
exception object back to the caller, use the C# throw keyword. Here is the relevant code update to the
Accelerate() method:
// This time, throw an exception if the user speeds up beyond MaxSpeed.
public void Accelerate(int delta)
{
if (carIsDead)
Console.WriteLine("{0} is out of order...", PetName);
else
{
CurrentSpeed += delta;
if (CurrentSpeed >= MaxSpeed)
{
carIsDead = true;
CurrentSpeed = 0;
// Use the "throw" keyword to raise an exception.
throw new Exception(string.Format("{0} has overheated!", PetName));
}
}
else
Console.WriteLine("=> CurrentSpeed = {0}", CurrentSpeed);
}
259