Errors and Exception Handling

When something goes wrong while a C# program is running, an exception occurs. Exceptions stop the current flow of the program, and if nothing is done, the program simply stops running. Exceptions can be caused by a bug in the program — for example, if a number is divided by zero — or can be a result of some unexpected input, such as a user selecting a file that doesn't exist. As a programmer, you need to allow your program to deal with these problems without crashing to a halt.

C# provides several keywords — try, catch, and finally — that allow programs to detect exceptions, deal with them, and continue running. They are a very useful tool for making your applications more reliable.

Try and Catch

The try and catch keywords are used together. Use try to enclose the block of code you are concerned might generate an exception, and catch to contain the code that will be executed if the exception occurs. In this example, a calculation creates a division by zero exception, which is then caught. Without the try and catch blocks, this program would fail.

class ProgramTryCatch
{
    static void Main()
    {
        int x=0, y=0;

        try
        {
            x = 10 / y;
        }

        catch (System.DivideByZeroException)
        {
            System.Console.WriteLine("There was an attempt to divide by zero.");
        }
    }
}

It's good programming practice to be specific about the type of exception your catch code is detecting. Each try can have multiple catch statements, each dealing with a different exception.

finally Blocks

Code contained in a finally block is always executed, whether or not an exception occurs. Use the finally block to make sure resources are returned: for example, to make sure that a file is closed.

try
{
    // Code to try here.
}
catch (SomeSpecificException ex)
{
    // Code to handle exception here.
}
finally
{
    // Code to execute after try (and possibly catch) here.
}

Using Exception Handling

Exceptions aren't always a sign that a catastrophic problem has occurred in your program. Often they are a convenient way of leaving a section of code that is no longer relevant, or a signal that a method has been unsuccessful. Many of the .NET Framework class methods create exceptions to warn of a particular condition.

You can also cause your own exceptions using the throw keyword. For example:

class ProgramThrow
{
    static void DoWork(int x)
    {
        if (x > 5)
        {
            throw new System.ArgumentOutOfRangeException("X is too large");
        }
    }

    static void Main()
    {
        try
        {
            DoWork(10);
        }
        catch (System.ArgumentOutOfRangeException ex)
        {
            System.Console.WriteLine(ex.Message);
        }
    }
}

Use exceptions in your programs when you think there is a chance of some unexpected situation arising. For example, when dealing with input from a user, reading a file or accessing information from the Internet.

See Also

Tasks

How to: Catch an Exception

Concepts

C# Language Primer

Reference

Exception Handling Statements (C# Reference)

throw (C# Reference)

try-catch (C# Reference)

try-finally (C# Reference)

try-catch-finally (C# Reference)