Developers often overlook the importance of exception handling to the detriment of their own code. In this article, I discuss how to use exception handling in C#. I also explain simple ways to add code snippets to application code to prevent users from seeing certain errors, which may cause applications to shut down.

Structured exception handling

The .NET Framework provides a standard mechanism for error reporting called structured exception handling. The mechanism relies on exceptions to report an error in the application.

In .NET, exceptions are classes that provide error information. You are expected to write code in a way that watches for exceptions generated by code and then deal with the exceptions in an appropriate manner.

When working with exceptions in C#, you need to take care of three components in the code:

|> The block of code that may result in an exception (this is also referred to as throwing an exception).
|> The block of code that will be executed in case there is an exception raised when the block of code is processed (this is also referred to as catching an exception).
|> The block of code that will be executed after the exception is processed (optional) (this is also referred to as the finally block).

Exception class

Exception classes in the .NET Framework are derived from a System.Exception class. Most utilised members of the class are listed below:

|> HelpLink is a link to a help file that provides information about the exception.
|> Message is text that specifies the details of an error.
|> Source is the name of the object or application that caused the exception.
|> StackTrace is the list of the method calls on the stack.
|> TargetSite is the name of the method that threw the exception.

Try/Catch/Finally block

To handle an exception in C#, a Try/Catch/Finally block is utilised.

|> Try statement specifies that you have a block of code that you should watch for exceptions thrown in while executing.
|> Catch statement specifies what code should be executed when an exception occurs.
|> Finally statement specifies the block of code that should be executed after a try code block executes. This block of code will be executed regardless of whether an exception occurs. In practice, it's often utilised for any clean up code you may require.

Catching all exceptions

.NET allows you to catch any exception that occurs in a particular block of code; however, you can also specify the exact exceptions to catch. Listing A shows an example of catching any exception.

Listing A

try
{
int i = 0;
int iresult;
iresult = 1 / i;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MessageBox.Show("finally block executed");
}

The code contains an error in order to demonstrate catching an exception. In Listing A, I catch any exception that may take place after the try keyword; I do this by declaring the variable ex of an Exception type. Regardless of the kind of error in this code, the statement in the catch block will execute. In addition, even if an error occurs (which it will in this case), the code in the finally block will execute.

Catching specific classes of exceptions

Listing B shows an example of catching a specific exception. The code contains an error in order to demonstrate catching an exception. In Listing B, I catch a specific exception (DivideByZeroException), which takes place when the code is executed; I do this by declaring the variable ex of a DivideByZeroException type. Only this kind of error would lead the execution to the statement after the catch keyword. In addition, even if an error occurs (which it will in this case), the code in the finally block will execute.

Listing B

try
{
int i = 0;
int iresult;
iresult = 1 / i;
}
catch (DivideByZeroException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MessageBox.Show("finally block executed");
}

Cast your .NET This was published in Cast your .NET, check every Thursday for more stories

Related links

Comments

1

Antonio - 24/04/07

Why don't you use the Microsoft Application Exception Block to simplify your code? Just plug in the namespace into you app.

» Report offensive content

2

eng.dody - 21/05/07

I HAVE AN ERROR IN MY CODE SAYS:Server Error in '/WebApplication4' Application.
--------------------------------------------------------------------------------

Maximum request length exceeded.
I WANT TO READ FROM DATAGRID ON XML FILE

private void Button1_Click(object sender, System.EventArgs e)
{
////////create xml file///////////


/*string myXMLfile = @"C:\\Documents and Settings\\AMonsef\\Desktop\\task\\b.xml";
//DataSet ds = new DataSet();
// Create new FileStream with which to read the schema////
System.IO.FileStream fsWriteXml = new System.IO.FileStream
(myXMLfile, System.IO.FileMode.Open);
try
{
ds.WriteXml(fsWriteXml);
datagrid1.DataSource = dt;
datagrid1.DataBind();
}
catch (Exception ex)
{
TextBox1.Text=(ex.ToString());
//MessageBox.Show(ex.ToString()));
}
finally
{
fsWriteXml.Close();
}*/

» Report offensive content

3

cyber sammy - 07/12/07

HI,

May I also suggest, that I find it very useful to plan, build and test the exception handling paths for the object prior to adding very much business code. So by building it and planning it, not just adding it as an afterthought, it is more robust and has more chance of working as desired.

cs.

» Report offensive content

4

jmneter - 08/08/08

5

pizixie - 29/08/08

why not supporting Chinese?
Why should I write by English?

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

5

pizixie - 29/08/08

why not supporting Chinese? Why should I write by English? ... more

4

jmneter - 08/08/08

dull ... more

3

cyber sammy - 12/07/07

HI, May I also suggest, that I find it very useful to plan, build and test the exception handling paths for the ... more

Log in


Sign up | Forgot your password?

  • Staff Apple to developer: Fart jokes aren't funny

    When Apple announced it would be vetting every application submitted for inclusion in the App Store, this was just the kind of question that entered many a mind: just how arbitrary would the company be in wielding that veto power? Read more »

    -- posted by Staff

  • Staff Chrome is just another browser

    Hands up if you missed the Chrome release -- didn't think anyone did. Google's browser arrived with all the fanfare and hype that only Google can produce. Read more »

    -- posted by Staff

  • Renai LeMay 2Vouch refers well

    Melbourne-based Web start-up 2Vouch yesterday launched the first public beta of what it dubs its "social recruiting platform". Read more »

    -- posted by Renai LeMay

What's on?