CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
Before examining how a caller would catch this exception, let’s look at a few points of interest. First
of all, when you are throwing an exception, it is always up to you to decide exactly what constitutes the
error in question, and when an exception should be thrown. Here, you are making the assumption that if
the program attempts to increase the speed of a Car object that has expired, a System.Exception object
should be thrown to indicate the Accelerate() method cannot continue (which may or may not be a
valid assumption; this will be a judgment call on your part based on the application you are creating).
Alternatively, you could implement Accelerate() to recover automatically without needing to throw
an exception in the first place. By and large, exceptions should be thrown only when a more terminal
condition has been met (for example, not finding a necessary file, failing to connect to a database, and
the like). Deciding exactly what justifies throwing an exception is a design issue you must always
contend with. For our current purposes, assume that asking a doomed automobile to increase its speed
is cause to throw an exception.
Catching Exceptions
Because the Accelerate() method now throws an exception, the caller needs to be ready to handle the
exception, should it occur. When you are invoking a method that may throw an exception, you make use
of a try/catch block. After you have caught the exception object, you are able to invoke the members of
the exception object to extract the details of the problem.
What you do with this data is largely up to you. You might wish to log this information to a report
file, write the data to the Windows event log, e-mail a system administrator, or display the problem to
the end user. Here, you will simply dump the contents to the console window:
// Handle the thrown exception.
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);
// Speed up past the car's max speed to
// trigger the exception.
try
{
for(int i = 0; i < 10; i++)
myCar. Accelerate(10);
}
catch(Exception e)
{
Console.WriteLine("\n*** Error! ***");
Console.WriteLine("Method: {0}", e.TargetSite);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
}
}
260
// The error has been handled, processing continues with the next statement.
Console.WriteLine("\n***** Out of exception logic *****");
Console.ReadLine();