236 Part II Programming Fundamentals
More Complex Try Catch Error Handlers
As your programs become more sophisticated, you might find it useful to write more
complex Try... Catch error handlers that manage a variety of run-time errors and unusual
error-handling situations. Try... Catch provides for this complexity by:
n Permitting multiple lines of code in each Try, Catch, or Finally code block.
n Using the Catch statement with particular Exception objects, which tests specific error
conditions.
n Allowing nested Try... Catch code blocks, which can be used to build sophisticated
and robust error handlers.
In addition, by using a special error-handling object named Exception, you can identify
and process specific run-time errors and conditions in your program. You’ll investigate each
of these error-handling features in the following section.
The Exception Object
The Microsoft .NET Framework provides the Exception object to help you learn about the
errors that occur in your programs. Exception provides you with information about the
exception that occurred so that you can respond to it programmatically. The most useful
Exception property is the Message property, which contains a short message about the error.
There are several different types of Exception objects. Table 9-2 lists the most important
Exception objects and what they mean.
TABLE 9-2 Important Exception Objects
Exception Description
ArgumentException Occurs when an argument passed to a method is not valid.
ArgumentOutOfRangeException Occurs when an argument is passed to a method that is outside
the allowable range.
ArithmeticException Occurs when there is an arithmetic-related error.
DataException Occurs when there is an error when accessing data using
ADO .NET.
DirectoryNotFoundException Occurs when a folder can’t be found.
DivideByZeroException Occurs when an attempt is made to divide by zero.
EndOfStreamException Occurs when an attempt is made to read past the end of
a stream.
Exception Occurs for any exception that is thrown. Other exceptions inherit
from this object.
FileNotFoundException Occurs when a file can’t be found.
IndexOutOfRangeException Occurs when an index is used that is outside the allowable range
of an array.