Database Reference
In-Depth Information
C H A P T E R 11
Handling Exceptions
For the programs you write, you definitely care about fixing any errors or problems that are brought to
your attention by the language compiler. However, there is a particular type of error that doesn't happen
during compile time; instead, it occurs at runtime. As you progress into more complex application
development, you have more chances of getting such runtime errors, known as
exceptions
. They can
occur because the application is trying to open a connection to a nonexistent database, open a file that
doesn't exist, or write to a file that is already open in read-only mode. This chapter will help you learn
more about exceptions and how to handle them when they occur.
The System.Exception Class
In .NET, all exceptions are derived from the
Exception
class. The
Exception
class is defined inside the
System
namespace. Other derived exception classes are spread across many other namespaces such as
SQLException
,
FileNotFoundException
,
IndexOutOfRangeException
, and so on.
Hence, when you invoke some .NET functionality and something goes wrong at runtime, a function
might throw an exception of a specific type. For example, if you connect to a nonexistent database, you
will receive a runtime error, in other words, an exception of type
SqlException
. Similarly, if you try to
open a file to read that doesn't exist, you will get a
FileNotFound
exception.
It is important to understand that all exceptions are derived from the
System.Exception
class. If you
catch
System.Exception
, for example, that would cover all exceptions derived from
System.Exception
also. I will demonstrate this later in this chapter. Table 11-1 shows the properties exposed by the
System.Exception
class.
Table 11-1.
System.Exception
Properties
Property Name
Description
Data
Gets a collection of key-value pairs that contain user-defined information
HelpLink
Specifies the help file associated with this exception
InnerException
Gets the exception instance that caused the current exception
Message
Defines the text describing the exception
Source
Specifies the name of the provider that generated the exception