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

Programmers Heaven: C# School

attempt to access the members of a class using a null reference. Lets change the code above a bit and assign an object to the reference 's'

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()");

}

catch(NullReferenceException e)

{

Console.WriteLine("In catch block...");

Console.WriteLine("NullReferenceException Caught");

}

Console.WriteLine("After try...catch block");

Since this program does not cause any exceptions to be raised, the execution of program will result into:

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

Faraz

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

After try...catch block

Press any key to continue

Exception class' Message and StackTrace Properties

Note that the code under the catch block didn't get executed because of the absence of NullReferenceException. Now lets remove the try...catch block, assign s to null as we did in the first place, and see what happens.

static void Main()

{

string s = null;

Console.WriteLine("Before printing lower case string...");

Console.WriteLine(s.ToLower());

Console.WriteLine("After printing lower case string...");

}

159

Programmers Heaven: C# School

When we compile and execute the above program, we see the following output:

Before printing lower case string...

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

at CSharpSchool.Test.Main() in

c:\documents and settings\administrator\my documents\visual studio projects\myconsole\class1.cs:line 11

Press any key to continue

Since we did not catch the NullReferenceException, our program got terminated prematurely with the runtime (CLR) reporting two things:

1.Exception Message: this describes the exception

2.Stack Trace of the cause of execution: This is the hierarchy of function calls which caused the exception. In our case it shows that the exception is caused by the Main() method of the Test class contained in the CSharpSchool namespace (CSharpSchool.Test.Main()). The Stack trace also points out the filename along with its complete path and the line number which contains the cause for the exception.

Because we don't want our program to crash when an exception occurs, we attempt to catch all the exceptions that can be caused by our code. Let's move to our previous code where we caught the NullReferenceException in the catch block. We can also print the Message and Stack Trace of the exception using the Message and the StackTrace property of the Exception class. Consider the following code:

static void Main()

{

string s = null; try

{

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

Console.WriteLine(s.ToLower());

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

}

catch(NullReferenceException e)

{

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

Console.WriteLine("NullReferenceException Caught");

Console.WriteLine("\nException Message");

Console.WriteLine("=============");

Console.WriteLine(e.Message);

Console.WriteLine("\nException Stack Trace");

160

Programmers Heaven: C# School

Console.WriteLine("==============");

Console.WriteLine(e.StackTrace);

}

Console.WriteLine("\nAfter try...catch block");

}

The difference between this one and the previous code is that here we have printed the explanatory message and stack trace of the exception explicitly by using the exception reference. The output of the program will be:

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

In catch block...

NullReferenceException Caught

Exception Message

=================

Object reference not set to an instance of an object.

Exception Stack Trace

=================

at CSharpSchool.Test.Main() in c:\documents and settings\administrator\ my documents\visual studio projects\myconsole\class1.cs:line 14

After try...catch block

Press any key to continue

The finally block

The optional finally block comes just after the try or catch block. The code in the finally block is guaranteed to always be executed whether an exception occurs or not in the try block. Usually, the finally block is used to free any resources acquired within the try block that could not be closed because of the exception. For example, the finally block can be used to close the file, database, socket connections and other important resources opened in the try block. Let's add the finally block to our previous example.

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()");

161

Programmers Heaven: C# School

}

catch(NullReferenceException e)

{

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

Console.WriteLine("NullReferenceException Caught");

}

finally

{

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

}

}

When we execute the program we see the following output:

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

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

In finally block...

Press any key to continue

Since no exception is raised, the code in the finally block is executed just after the code in the try block. Lets cause an exception to occur by setting the string 's' to null in Main()

static void Main()

{

string s = null;

...

}

Now the output will be:

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

In catch block...

NullReferenceException Caught

In finally block...

Press any key to continue

The output shows that the code in the finally block is always executed after the execution of the try and catch block regardless of if an exception occurred or not.

162

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