Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index



Sometimes unexpected situations arise during the execution of a program. Careful programmers write code that detects errors and deals with them appropriately. However, a simple algorithm can become unintelligible when error-checking is added because the error-checking code can obscure the normal operation of the algorithm.

Exceptions  provide a clean way to detect and handle unexpected situations. When a program detects an error, it throws  an exception. When an exception is thrown, control is transfered to the appropriate exception handler . By defining a method that catches the exception, the programmer can write the code to handle the error.

In C#, an exception is an object. All exceptions in C# are ultimately derived from the base class called System.Exception. For example, consider the class A defined in Program gif. Since the A class extends the System.Exception class, A is an exception that can be thrown.

Program: Using exceptions in C#.

A method throws an exception by using the throw statement: The throw statement is similar to a return statement. A return statement represents the normal termination of a method and the object returned matches the return value of the method. A throw statement represents the abnormal termination of a method and the object thrown represents the type of error encountered. The F method in Program gif throws an A exception.

Exception handlers are defined using a try block: The body of the try block is executed either until an exception is thrown or until it terminates normally. One or more exception handlers follow a try block. Each exception handler consists of a catch clause which specifies the exceptions to be caught, and a block of code, which is executed when the exception occurs. When the body of the try block throws an exception for which an exception is defined, control is transfered to the body of the exception handler.

In this example, the exception thrown by the F method is caught by the G method. In general when an exception is thrown, the chain of methods called is searched in reverse (from caller to callee) to find the closest matching catch statement. When a program throws an exception that is not caught, the program terminates.

next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.