You are currently offline, waiting for your internet to reconnect

How to use structured exception handling in Visual C# .NET and in Visual C# 2005 or Visual C# 2008

SUMMARY
This article describes how to use structured exception handling in Microsoft Visual C# .NET, in Microsoft Visual C# 2005, or in Microsoft Visual C# 2008.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Visual C# .NET or later versions of Visual C#

This article assumes that you are familiar with the following topics:
  • Visual C# .NET or later versions of Visual C#
  • Microsoft Visual Studio .NET or or later versions of Visual Studio
back to the top

Structured Exception Handling

Visual C# .NET offers structured exception handling that provides a powerful and a more readable way to handle errors. Structured exception handling enables you to nest error handlers inside other error handlers that are in the same procedure. Structured exception handling uses a block syntax that is similar to the If...Else...End If statement. This makes Visual C# .NET code or code in later versions of Visual C# more readable and easier to maintain. You can handle exceptions in Visual C# .NET or in later versions Visual C# by using a combination of exception handling statements:
  • try
  • catch
  • finally
  • throw
The basic syntax of structured error handling is as follows:
try{  // Code that is expected to raise an exception.}catch(Exception e){  // Code that can handle an error.}finally{  // Code to do any final cleanup.}
You can include any valid Visual C# code in the try block, or you can include another try block or another hierarchy of try blocks. When an exception occurs at any point, the common language runtime looks for the nearest try block that encloses this code and does not run any additional lines of code. The control is then passed to a matching catch block, if one exists, and to the associated finally block. You can also specify multiple catch statements so that each catch block handles a specific error.

back to the top

Catch an Exception

  1. In Microsoft Visual Studio.NET, click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.

    In Microsoft Visual Studio 2005, click Start, point to Programs, point toMicrosoft Visual Studio 2005, and then click Microsoft Visual Studio 2005.

    In Microsoft Visual Studio 2008, click Start, point to Programs, point toMicrosoft Visual Studio 2008, and then click Microsoft Visual Studio 2008..
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, follow these steps:
    1. Under Project Types, click Visual C# Projects.

      Note In Visual Studio 2005 or in Visual Studio 2008, click Visual C# under Project Types.
    2. Under Templates, click Console Application.
    3. In the Name box, type MyConsoleApp.
    4. In the Location box, type C:\, and then click OK.
  4. Add the following code in the Main() function:
    int a = 0;			int b = 10;			int c = 0;			try 			{				a = b / c;			}			catch (Exception e)			{				Console.WriteLine("A run-time error occurred.");			}			finally 			{				Console.ReadLine();			}
  5. To run the application, click Start on the Debug menu. The code tries to divide a number by 0. This operation is not valid and causes a divide-by-zero error. However, the catch block catches this error, and the Console window displays the following error message:

    A run-time error occurred
  6. Close the Console window.
back to the top

Catch Multiple Exceptions

This section demonstrates how to use multiple catch statements to handle different errors.
  1. Open the Console Application project that you created in the "Catch an Exception" section of this article.
  2. Replace the existing code in the Main() function with the following code:
    int a = 2147483647;			int b = 0;			int c = 0;			try 			{				 a = checked(a + 1);			}			catch (DivideByZeroException e)			{				Console.WriteLine("Error: Divide by Zero", e.Message);			}			catch (OverflowException e)			{				Console.WriteLine("Error: Overflow", e.Message);			}			finally 			{				Console.ReadLine();			}
    This code includes two catch blocks:
    • One catch block catches the previous divide-by-zero error.
    • One catch block catches the new overflow error.
  3. To run the application, click Start on the Debug menu. The Console window displays the following error message:
    Error: Overflow
  4. Close the Console window.
  5. Because you cannot always anticipate every error that may occur, you can add a catch block for all exceptions that you cannot anticipate. For example, add the following code before the finally statement to catch any errors that you cannot anticipate and to display the appropriate error message:
    catch (Exception e)			{				Console.WriteLine("Error: ", e.Message);			}
  6. On the File menu, click Close Solution.
back to the top

Throw an Exception

Structured exception handling uses the catch statement to catch an exception. With structured exception handling, you can also throw an exception. For example, you may find it useful to throw an exception when you perform data validation inside a Property Set procedure, because you may want to throw an error if a business rule is violated.
  1. In Microsoft Visual Studio.NET, click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.

    In Microsoft Visual Studio 2005, click Start, point to Programs, point toMicrosoft Visual Studio 2005, and then click Microsoft Visual Studio 2005.

    In Microsoft Visual Studio 2008, click Start, point to Programs, point toMicrosoft Visual Studio 2008, and then click Microsoft Visual Studio 2008..
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, follow these steps:
    1. Under Project Types, click Visual C# Projects.

      Note In Visual Studio 2005 or in Visual Studio 2008, click Visual C# under Project Types.
    2. Under Templates, click Console Application.
    3. In the Name box, type MyNewConsoleApp.
    4. In the Location box, type C:\, and then click OK.
  4. On the Project menu, click Add Class.
  5. In the Add New Item dialog box, type clsPerson.cs in the Name box, and then click Open.

    Note In Visual Studio 2005 or in Visual Studio 2008, click Add.
  6. Add the following code in the clsPerson class:
    public clsPerson()		{		}		private int mintAge;		public int Value;		public int Age		{			get			{				Age = mintAge;				return Age;			}			set			{				if(Value > 0)					mintAge = Value;				else					throw new ArgumentException("Age cannot be negative.");			}		}
    This code creates an Age property. Because a person cannot have a negative age, an error is raised if the user of the class tries to set the Age property to a number that is less than 0.
  7. In the Main() function of Class1.cs, add the following code:
    clsPerson p = new clsPerson();			try 			{				p.Age = -1;			}			catch (Exception e)			{				Console.WriteLine(e.Message);			}			finally			{				Console.ReadLine();			}
  8. To run the application, click Start on the Debug menu. The Console window displays the following error message:
    Age cannot be negative
  9. Close the Console window.
back to the top

Complete Code Listing

Catch an Exception

using System;namespace MyConsoleApp{	class Class1	{		[STAThread]  static void Main(string[] args)		{			int a = 0;			int b = 0;			int c = 0;			try 			{				a = b / c;			}			catch (Exception e)			{				Console.WriteLine("A run-time error occurred.");			}			finally 			{				Console.ReadLine();			}		}}}

Catch Multiple Exceptions

using System;namespace MyConsoleApp{	class Class1	{		[STAThread]		static void Main(string[] args)		{			int a = 2147483647;					try 			{				a = checked(a + 1);			}			catch (DivideByZeroException e)			{				Console.WriteLine("Error: Divide by Zero", e.Message);			}			catch (OverflowException e)			{				Console.WriteLine("Error: Overflow", e.Message);			}			catch (Exception e)			{				Console.WriteLine("Error: ", e.Message);			}			finally 			{				Console.ReadLine();			}		}	}}

Throw an Exception

using System;namespace MyNewConsoleApp{	class Class1	{				[STAThread]		static void Main(string[] args)		{			clsPerson p = new clsPerson();			try 			{				p.Age = -1;			}			catch (Exception e)			{				Console.WriteLine(e.Message);			}			finally			{				Console.ReadLine();			}		}	}public class clsPerson	{		public clsPerson()		{		}		private int mintAge;		public int Value;		public int Age		{			get			{				Age = mintAge;				return Age;			}			set			{				if(Value > 0)					mintAge = Value;				else					throw new ArgumentException("Age cannot be negative.");			}		}	}}
back to the top
REFERENCES
For more information, visit the following Microsoft Web site:
Exception Management Application Block for .NET
http://msdn2.microsoft.com/en-us/library/ms954830.aspx
back to the top
Properties

Article ID: 816157 - Last Review: 07/16/2008 18:50:00 - Revision: 3.1

  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# 2008 Express Edition
  • kbprogramming kbexcepthandling kbhowtomaster KB816157
Feedback
>