*/
Know a good article or link that we're missing? Submit it!

Other Views

corner
*/

Exception handling with Try..Catch and Finally Blocks

Previous Page        Next Page



Handling Exceptions using the try...catch...finally blocks


Use of the try...catch block
A simple demonstration of the use of the try...catch blocks is given below.

	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("In catch block...");
			Console.WriteLine("NullReferenceException Caught");
		}
		Console.WriteLine("After try...catch block");
	}


The string 's' in Main() is assigned a null value. When we attempt to call the ToLower() method on this null reference in the Console.WriteLine() method, the CLR (Common Language Runtime) will raise the NullReferenceException. Since we have enclosed the call to the ToLower() method in a try block, the Runtime will search for a catch block which can catch this exception and, if one is found, the execution will jump to this catch block. The syntax of the catch block is important to understand. In parenthesis after the catch, a reference ('e' in our case) of our target exception class is declared (NullReferenceException in our case). When the above program is executed, the output is:

In try block... before calling s.ToLower()
In catch block...
NullReferenceException Caught
After try...catch block
Press any key to continue


Look carefully at the output of the program and compare it with the source code. The call to s.ToLower() raises the NullReferenceException. As a result, the execution of the remaining part of the try block is ignored and the program execution is transferred to the catch block. Remember that the NullReferenceException is raised when we 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...");
	}


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("=================\n");
			Console.WriteLine(e.Message);
				
			Console.WriteLine("\nException Stack Trace");
			Console.WriteLine("=====================\n");
				
			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 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



Previous Page        Next Page



corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.