Exception Handling Overview

Programs frequently test conditions to determine how program execution should proceed. Consider the following pseudocode:

Perform a task

If the preceding task did not execute correctly

      Perform error processing

Perform next task

If the preceding task did not execute correctly

      Perform error processing

...

In this pseudocode, we begin by performing a task; then we test whether that task executed correctly. If not, we perform error processing. Otherwise, we continue with the next task. Although this form of error handling works, intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debugespecially in large applications.

Exception handling enables programmers to remove error-handling code from the "main line" of the program's execution, improving program clarity and enhancing modifiability. Programmers can decide to handle any exceptions they chooseall exceptions, all exceptions of a certain type or all exceptions of a group of related types (i.e., exception types that are related through an inheritance hierarchy). Such flexibility reduces the likelihood that errors will be overlooked, thus making programs more robust.

With programming languages that do not support exception handling, programmers often delay writing error-processing code and sometimes forget to include it. This results in less robust software products. C# enables programmers to deal with exception handling easily from the beginning of a project.

Категории