Export (0) Print
Expand All

Exceptions and Exception Handling (C# Programming Guide)

The C# language's exception handling features provide a way to deal with any unexpected or exceptional situations that arise while a program is running. Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards. Exceptions can be generated by the common language runtime (CLR), by third-party libraries, or by the application code using the throw keyword.

In this example, a method tests for a division by zero, and catches the error. Without the exception handling, this program would terminate with a DivideByZeroException was unhandled error.

int SafeDivision(int x, int y)
{
    try
    {
        return (x / y);
    }
    catch (System.DivideByZeroException dbz)
    {
        System.Console.WriteLine("Division by zero attempted!");
        return 0;
    }
}

Exceptions have the following properties:

  • When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated.

  • Use a try block around the statements that might throw exceptions.

  • Once an exception occurs within the try block, the flow of control immediately jumps to an associated exception handler, if one is present.

  • If no exception handler for a given exception is present, the program stops executing with an error message.

  • If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.

  • Actions that may result in an exception are executed with the try keyword.

  • An exception handler is a block of code that is executed when an exception occurs. In C#, the catch keyword is used to define an exception handler.

  • Exceptions can be explicitly generated by a program using the throw keyword.

  • Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.

  • Code in a finally block is executed even if an exception is thrown, thus allowing a program to release resources.

For more information, see the following sections in the C# Language Specification:

  • 8.9.5 The throw statement

  • 8.10 The try statement

  • 16 Exceptions

Community Additions

ADD
Show:
© 2014 Microsoft