Information Technology Reference
In-Depth Information
The catch Clause
The
catch
clause handles exceptions. There are three forms of the
catch
clause, allowing differ-
ent levels of processing. The forms are shown in Figure 11-3.
Figure 11-3.
The three forms of the catch clause
The
general
catch
clause
can accept any exception, but cannot determine the type of
exception that caused it. This allows general processing and cleanup for whatever exception
might occur.
The
specific
catch
clause
form takes the name of an exception class as a parameter. It
matches exceptions of the specified class or exception classes derived from it.
The
specific
catch
clause with ID
form gives you the most information about the exception.
It matches exceptions of the specified class, or exception classes derived from it. It also gives
you an exception instance ID, called the
exception variable
, which is a reference to the excep-
tion object created by the CLR. You can access the exception variable's properties within the
block of the
catch
clause to get specific information about the exception raised.
For example, the following code handles exceptions of type
IndexOutOfRangeException
.
When one occurs, a reference to the actual exception object is passed into the code with
parameter name
e
. The three
WriteLine
statements each read a string field from the excep-
tion object.
Exception type
Exception variable
↓
↓
catch ( IndexOutOfRangeException e )
{
Accessing the exception variable
↓
Console.WriteLine( "Message: {0}", e.Message );
Console.WriteLine( "Source: {0}", e.Source );
Console.WriteLine( "Stack: {0}", e.StackTrace );