Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
77
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

It is possible to write the try...finally block without any catch block, e.g.:

static void Main()

{

string s = "Faraz"; try

{

Console.WriteLine("In try block... before calling s.ToLower()");

Console.WriteLine(s.ToLower());

Console.WriteLine("In try block... after calling s.ToLower()");

}

finally

{

Console.WriteLine("\nIn finally block...");

}

}

The output of the program will be:

In try block... before calling s.ToLower() faraz

In try block... after calling s.ToLower()

In finally block...

Press any key to continue

The output of the program shows that the finally block is always executed after the try block.

Catching Multiple Exceptions using multiple catch blocks

It is possible to catch multiple (different) exceptions that may be thrown in a try block using multiple (or a series of) catch blocks. For example, we can write three catch blocks; one for catching the NullReferenceException, second for catching the IndexOutOfRangeException and the third is for any other exception (Exception). Remember that the IndexOutOfRangeException is raised when an element of an array whose index is out of the range of the array is accessed. An out of range index can be either less than zero, or greater than or equal to size of the array. The code below demonstrates the use of multiple catch blocks.

static void Main()

{

string s = "Faraz";

int []i = new int[3];

163

Programmers Heaven: C# School

try

{

Console.WriteLine("Entering the try block...\n");

//can cause NullReferenceException Console.WriteLine("Lower case name is: " + s.ToLower());

//can cause NullReferenceException or IndexOutOfRangeException Console.WriteLine("First element of array is: " + i[0].ToString());

//can cause DivideByZeroException

i[0] = 3;

i[1] = 4/i[0];

Console.WriteLine("\nLeaving the try block...");

}

catch(NullReferenceException e)

{

Console.WriteLine("\nIn catch block...");

Console.WriteLine("NullReferenceException Caught");

}

catch(IndexOutOfRangeException e)

{

Console.WriteLine("\nIn catch block...");

Console.WriteLine("IndexOutOfRangeException Caught");

}

catch(Exception e)

{

Console.WriteLine("\nIn catch block...");

Console.WriteLine("Exception Caught");

Console.WriteLine(e.Message);

}

}

Here we have used a string 's' and an integer array i. The size of the int array is declared as 3. There are three places in the program where we will introduce the occurrence of exceptions:

's' and 'i' can be null, causing a NullReferenceException.

Access to the array 'i' may cause an IndexOutOfRangeException

The division of 4 by i[0] may cause a DivideByZeroException if the value of i[0] is zero.

164

Programmers Heaven: C# School

We have declared the three catch blocks in the code for each of these types of exception. Note that the last catch block is designed to catch any other exception except NullReferenceException and IndexOutOfRangeException, which have already been caught above it.

Only one of these exceptions can be raised, which will terminate the execution of the try block and will transfer the execution to the respective catch block. When the above code is executed we will see the following output:

Entering the try block...

Lower case name is: faraz

First element of array is: 0

Leaving the try block...

Press any key to continue

So far so good...no exception has occurred. Let us first make the string reference s null and see the effect.

static void Main()

{

string s = null;

...

}

The output will be:

Entering the try block...

In catch block...

NullReferenceException Caught

Press any key to continue

It looks similar and is very much as expected. Now change the array index to some out of bound value (either less than zero or greater than or equal to 3). Also change the string 's' to point to some string to avoid the NullReferenceException.

Console.WriteLine("Sixth element of array is: " + i[5].ToString());

The output will expectedly be:

Entering the try block...

165

Programmers Heaven: C# School

Lower case name is: faraz

In catch block...

IndexOutOfRangeException Caught

Press any key to continue

Finally correct the access to the array using a valid index and make the value of i[0] equal to zero to cause the DivideByZeroException

...

i[0] = 0;

...

The output of the program will be:

Entering the try block...

Lower case name is: faraz

First element of array is: 0

In catch block...

Exception Caught

Attempted to divide by zero.

Press any key to continue

The execution of 3/i[0] has caused a DivideByZeroException. The runtime checked for the presence of a catch block. In the third catch block it found an Exception, which is the super type of the DivideByZeroException (and any other exception in .Net). The execution was then transferred to that corresponding catch block.

An important point to remember in multiple catch blocks

Since exceptions are present in .Net as classes and objects, they follow the inheritance hierarchy. This means that if you write a catch block to handle a base class exception, it will automatically handle all of its sub-class' exceptions. Attempting to catch any of the sub-class exceptions explicitly after the parent class exception, will cause a compile time error. For example, consider the following code:

static void Main()

{

string s = null;

try

{

Console.WriteLine("Entering the try block...\n");

// can cause NullReferenceException

Console.WriteLine("Lower case name is: " + s.ToLower());

166

Соседние файлы в папке books