BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Exception Handling

The thirty-fourth part of the C# Fundamentals tutorial begins a review of exception handling. When an unexpected event occurs, unhandled exceptions cause a program to exit abnormally. Correct handling permits the graceful recovery from an error condition.

The Basic Try / Catch Block

C# provides a code structure known as the try / catch block that permits the handling of exceptions. A basic try / catch block has two elements. The try section contains one or more commands to be executed, held within brace characters { and }. The catch section contains code to execute if an exception occurs during processing of the try section. The basic syntax is as follows:

try
{
    // commands to execute whilst checking for exceptions
}
catch
{
    // commands to execute if an exception occurs
}

When using this basic syntax, any exception that occurs causes the code in the try block to be left and the code in the catch block to be executed. The catch block can be used for various purposes including graceful recovery from the error, logging or reporting of the details of the problem, and freeing up resources such as database connections or open files. Once the catch block has finished executing, or if no exception occurs within the try block, the program continues with the next statement after the try / catch structure.

The following example throws an exception by attempting to divide by zero. In this case, a message is reported to the user and the calculated value is set to the highest possible integer value.

static void Main(string[] args)
{
    int value = 50;
    int divisor = 0;
    int calculated;

    try
    {
        calculated = value / divisor;
    }
    catch
    {
        Console.WriteLine("An error occurred during division.");
        calculated = int.MaxValue;
    }

    Console.WriteLine("Result = {0}", calculated);
}

/* OUTPUT

An error occurred during division.
Result = 2147483647

*/

Extracting Exception Information

As described earlier, the throwing of an exception includes the generation of an exception object. The object has properties containing information describing the error. This can be read by the code within the catch block by adding an exception declaration to the catch statement. The following example extends the previous code by declaring an object of the most generalised Exception class. All exceptions will be caught but now the exception information may be used when generating the error message.

static void Main(string[] args)
{
    int value = 50;
    int divisor = 0;
    int calculated;

    try
    {
        calculated = value / divisor;
    }
    catch (Exception ex)                        // Catch any exception
    {
        Console.WriteLine("An error occurred during division.");
        Console.WriteLine(ex.Message);          // Report the error message
        calculated = int.MaxValue;
    }

    Console.WriteLine("Result = {0}", calculated);
}

/* OUTPUT

An error occurred during division.
Attempted to divide by zero.
Result = 2147483647

*/

The above example catches any exception and populates an object of class Exception. The Message property of the object is used to output an error description. This is one of several properties that are provided by all exception classes. Some of the most useful properties are:

  • Message. A string providing a description of the exception.
  • Source. A string containing the name of the program or object that caused the exception.
  • TargetSite. An object containing details of the method that caused the exception.
  • StackTrace. A string containing the complete stack of calls that led to the exception. This string allows the programmer to review each method call made up until the exception occurred. This is especially useful during testing and debugging.
  • InnerException. When one exception occurs as the direct result of another, the initial exception may be held in this property. The inner exception contains all of the standard properties including, potentially, a further InnerException. If there is no inner exception, this property is null.

NB: More specialised exception types include further relevant information. For example, the ArgumentException includes a 'ParamName' property detailing the parameter in question.

static void Main(string[] args)
{
    int value = 50;
    int divisor = 0;
    int calculated;

    try
    {
        calculated = value / divisor;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Message:    {0}\n", ex.Message);
        Console.WriteLine("Source:     {0}\n", ex.Source);
        Console.WriteLine("TargetSite: {0}\n", ex.TargetSite.Name);
        Console.WriteLine("StackTrace: {0}\n", ex.StackTrace);

        calculated = int.MaxValue;
    }

    Console.WriteLine("Result = {0}", calculated);
}

/* OUTPUT

Message:    Attempted to divide by zero.

Source:     ConsoleApplication1

TargetSite: Void Main(System.String[])

StackTrace: at ConsoleApplication1.Program.Main(String[] args) in
            C:\...\Program.cs:line 17

Result = 2147483647

*/
29 March 2007