Microsoft KB Archive/816157

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

Article ID: 816157

Article Last Modified on 11/26/2007

-

APPLIES TO


 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# 2005 Express Edition

-





For a Microsoft Visual Basic .NET version of this article, see 315965.

IN THIS TASK

 * SUMMARY
 * Requirements
 * Structured Exception Handling
 * Catch an Exception
 * Catch Multiple Exceptions
 * Throw an Exception
 * Complete Code Listing
 * Catch an Exception
 * Catch Multiple Exceptions
 * Throw an Exception
 * REFERENCES



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

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 Visual C# 2005

This article assumes that you are familiar with the following topics:
 * Visual C# .NET or Visual C# 2005
 * Microsoft Visual Studio .NET or Microsoft Visual Studio 2005

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 or Visual C# 2005 code more readable and easier to maintain. You can handle exceptions in Visual C# .NET or Visual C# 2005 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
 Click Start, point to Programs, point to Microsoft Visual Studio .NET or Microsoft Visual Studio 2005, and then click Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. In the New Project dialog box, follow these steps:  Under Project Types, click Visual C# Projects.

Note In Visual Studio 2005, click Visual C# under Project Types. Under Templates, click Console Application. In the Name box, type MyConsoleApp . In the Location box, type C:\, and then click OK.</li></ol> </li>  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(&quot;A run-time error occurred.&quot;); }           finally {               Console.ReadLine; } </li> 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

</li> Close the Console window.</li></ol>

back to the top

Catch Multiple Exceptions
This section demonstrates how to use multiple catch statements to handle different errors. <ol> Open the Console Application project that you created in the &quot;Catch an Exception&quot; section of this article.</li>  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(&quot;Error: Divide by Zero&quot;, e.Message); }           catch (OverflowException e)            { Console.WriteLine(&quot;Error: Overflow&quot;, e.Message); }           finally {               Console.ReadLine; } This code includes two catch blocks: <ul> One catch block catches the previous divide-by-zero error.</li> One catch block catches the new overflow error.</li></ul> </li> To run the application, click Start on the Debug menu. The Console window displays the following error message:

Error: Overflow

</li> Close the Console window.</li>  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(&quot;Error: &quot;, e.Message); } </li> On the File menu, click Close Solution.</li></ol>

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. <ol> Click Start, point to Programs, point to Microsoft Visual Studio .NET or Microsoft Visual Studio 2005, and then click Microsoft Visual Studio .NET or Microsoft Visual Stuio 2005.</li> On the File menu, point to New, and then click Project.</li> In the New Project dialog box, follow these steps: <ol style="list-style-type: lower-alpha;"> Under Project Types, click Visual C# Projects.

Note In Visual Studio 2005, click Visual C# under Project Types.</li> <li>Under Templates, click Console Application.</li> <li>In the Name box, type MyNewConsoleApp .</li> <li>In the Location box, type C:\, and then click OK.</li></ol> </li> <li>On the Project menu, click Add Class.</li> <li>In the Add New Item dialog box, type clsPerson.cs in the Name box, and then click Open.

Note In Visual Studio 2005, click Add.</li> <li> 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(&quot;Age cannot be negative.&quot;); }       }  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. </li> <li> 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; } </li> <li>To run the application, click Start on the Debug menu. The Console window displays the following error message:

Age cannot be negative

</li> <li>Close the Console window.</li></ol>

back to the top

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(&quot;A run-time error occurred.&quot;); }           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(&quot;Error: Divide by Zero&quot;, e.Message); }           catch (OverflowException e)            { Console.WriteLine(&quot;Error: Overflow&quot;, e.Message); }           catch (Exception e)            { Console.WriteLine(&quot;Error: &quot;, 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(&quot;Age cannot be negative.&quot;); }       }    } } back to the top

<div class="references_section">