SUMMARY
This article
describes how to use structured exception handling in Microsoft Visual C#
.NET or Microsoft Visual C# 2005.
back to the topRequirements
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 topStructured 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:
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 topCatch 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.
- 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();
}
- 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 - Close the Console window.
back to the
topCatch Multiple Exceptions
This section demonstrates how to use multiple
catch
statements to handle different errors.
- Open the Console Application project that you created in
the "Catch an Exception" section of this article.
- 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.
- To run the application, click Start on the Debug menu. The Console
window displays the following error message:
Error: Overflow
- Close the Console window.
- 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);
}
- On the File menu, click Close
Solution.
back to the
topThrow 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.
- 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.
- 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 MyNewConsoleApp.
- In the Location box, type
C:\, and then click OK.
- On the Project menu, click Add
Class.
- 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. - 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. - 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();
}
- To run the application, click Start on the Debug menu. The Console window displays the
following error message:
Age cannot be negative
- Close the Console window.
back to the
topComplete 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