CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
static void Main(string[] args)
{
Console.WriteLine("***** Handling Multiple Exceptions *****\n");
Car myCar = new Car("Rusty", 90);
try
{
// Trip Arg out of range exception.
myCar.Accelerate(-10);
}
catch (CarIsDeadException e)
{
Console.WriteLine(e.Message);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
When you are authoring multiple catch blocks, you must be aware that when an exception is
thrown, it will be processed by the “first available” catch. To illustrate exactly what the “first available”
catch means, assume you retrofitted the previous logic with an additional catch scope that attempts to
handle all exceptions beyond CarIsDeadException and ArgumentOutOfRangeException by catching a
general System.Exception as follows:
// This code will not compile!
static void Main(string[] args)
{
Console.WriteLine("***** Handling Multiple Exceptions *****\n");
Car myCar = new Car("Rusty", 90);
}
272
try
{
// Trigger an argument out of range exception.
myCar.Accelerate(-10);
}
catch(Exception e)
{
// Process all other exceptions?
Console.WriteLine(e.Message);
}
catch (CarIsDeadException e)
{
Console.WriteLine(e.Message);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();