C# Tutorial - Dissecting Our Fourth Application - 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. Exceptions are classes that provide error information, so therefore you write code in a way that watches for exceptions to be generated by code and then deal with the exceptions in an appropriate manner.

There are three components to handling exceptions.

  • The block of code that may result in an exception (referred to as throwing an exception).

  • The block of code that will be executed in case an exception is raised when the block of code is processed (referred to as catching an exception).

  • The block of code that will be executed after the exception is processed (optional) (referred to as the finally block).

This can be shown in some simple code:

try
{
  int i = 1/0; // Code to throw exception
}
catch (Exception ex)
{
  .. // Code to do something when exception is thrown
}
finally
{
  .. // Code to do something every time an exception is thrown
}

Where:

  • The try statement specifies that the enclosed block of code should be watched for exceptions to be thrown while executing.

  • The catch statement specifies what code should be executed when an exception occurs.

  • The finally statement specifies the block of code that will always be executed after a try-catch code block executes. This block of code will be executed regardless of whether an exception occurs.

Exception classes are derived from the System.Exception class. Some useful properties are listed here:

  • HelpLink - A link to the help file that provides information about this exception.

  • Message - A message that describes the current exception.

  • Source - The name of the application or the object that caused the error.

  • StackTrace - A string representation of the method calls on the call stack at the time the current exception was thrown.

  • TargetSite - The name of the method that threw the current exception.

Specific Exceptions

When an exception occurs in your code, a specific exception is thrown. Once you know the type of exception, then you can cater for it in your code as in App04.

If you enter a non whole number when asked in App03, the dialog above appear and states that a "FormatException was unhandled". This occurred because the Convert class could not convert the entered value, which was a floating point number such as 23.4, into a 32-bit integer.

Clicking on View Details action allows more information to be shown about the exception that was thrown.

It is often in this manner when play testing, that most exceptions can be catered for. Hence in the listing for App04, we cater for this exact exception.

catch (System.FormatException)
{
 . . .
}

<< Previous Contents Next >>

© Publicjoe, 2008