BlackWaspTM
C# Programming
.NET 1.1+

C# Exception Handling (2)

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

*/
29 March 2007