Partager via


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 Overview

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.

  • Once an exception occurs, 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.

  • 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.

See the following topics for more information about exceptions and exception handling:

C# Language Specification

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

See Also

Reference

C# Keywords
throw (C# Reference)
try-catch (C# Reference)
try-finally (C# Reference)
try-catch-finally (C# Reference)

Concepts

C# Programming Guide
Exceptions Overview

Other Resources

Handling and Throwing Exceptions