Free mag vol1 | Page 333

CHAPTER 7  UNDERSTANDING STRUCTURED EXCEPTION HANDLING Figure 7-1. The Exception code snippet template  Source Code The CustomException project is included under the Chapter 7 subdirectory. Processing Multiple Exceptions In its simplest form, a try block has a single catch block. In reality, though, you often run into situations where the statements within a try block could trigger numerous possible exceptions. Create a new C# Console Application project named ProcessMultipleExceptions, add the Car.cs, Radio.cs, and CarIsDeadException.cs files from the previous CustomException example into the new project (via Project  Add Existing Item), and update your namespace names accordingly. Now, update the Car’s Accelerate() method to also throw a predefined base class library ArgumentOutOfRangeException if you pass an invalid parameter (which we will assume is any value less than zero). Note the constructor of this exception class takes the name of the offending argument as the first string, followed by a message describing the error. // Test for invalid argument before proceeding. public void Accelerate(int delta) { if(delta < 0) throw new ArgumentOutOfRangeException("delta", "Speed must be greater than zero!"); ... } The catch logic could now specifically respond to each type of exception: 271