array of four elements. However, the
Although quite short, the preceding program illustrates several key points about exception
handling. First, the code that you want to monitor for errors is contained within a
try
terminated. That is,
catch
called. Rather, program execution is transferred to it. Thus,
Thus, it is the job of your exception handler to remedy the problem that caused the
340
P a r t I :
T h e C # L a n g u a g e
Notice that no exception variable is specified in the
catch
clause. Instead, only the type
of the exception (
IndexOutOfRangeException
in this case) is required. As mentioned, an
exception variable is needed only when access to the exception object is required. In some
cases, the value of the exception object can be used by the exception handler to obtain
additional information about the error, but in many cases, it is sufficient to simply know
that an exception occurred. Thus, it is not unusual for the
catch
variable to be absent in the
exception handler, as is the case in the preceding program.
As explained, if no exception is thrown by a
try
block, no
catch
will be executed and
program control resumes after the
catch
. To confirm this, in the preceding program, change
the
for
loop from
for(int i=0; i < 10; i++) {
to
for(int i=0; i < nums.Length; i++) {
Now, the loop does not overrun
nums
’ boundary. Thus, no exception is generated, and the
catch
block is not executed.
A Second Exception Example
It is important to understand that all code executed within a
try
block is monitored for
exceptions. This includes exceptions that might be generated by a method called from
within the
try
block. An exception thrown by a method called from within a
try
block
can be caught by that
try
block, assuming, of course, that the method itself did not catch
the exception.
For example, consider the following program.
Main( )
establishes a
try
block from which
the method
GenException( )
is called. Inside
GenException( )
, an
IndexOutOfRangeException
is generated. This exception is not caught by
GenException( )
. However, since
GenException( )
was called from within a
try
block in
Main( )
, the exception is caught by the
catch
statement
associated with that
try
.
/* An exception can be generated by one
method and caught by another. */
using System;
class ExcTest {
// Generate an exception.
public static void GenException() {
int[] nums = new int[4];
Console.WriteLine("Before exception is generated.");
// Generate an index out-of-bounds exception.
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
www.freepdf-books.com