Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
C++ How to Program, 5/e

ISBN:
0-13-185757-6
© 2005
pages: 1500
Buy the Book!
Amazon logo
InformIT logo

This tutorial introduces C++ exception handling. An exception is an indication of a problem that occurs during a program's execution. The name "exception" implies that the problem occurs infrequently—if the "rule" is that a statement normally executes correctly, then the "exception to the rule" is that a problem occurs. The techniques presented in this tutorial enable programmers to write robust, fault-tolerant programs that are able to deal with problems that may arise, and continue executing or terminate gracefully. We demonstrate exception-handling techniques with an example in which a function generates an exception when an attempt is made to divide by zero. The program catches this exception, issues an error message, then continues normal execution. This tutorial is intended for students and professionals who are already familiar with building C++ classes.

Download the code examples for this tutorial.

[Note: This tutorial is an excerpt (Section 16.3) of Chapter 16, Exception Handling, from our textbook C++ How to Program, 5/e. These tutorials may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., C++ HOW TO PROGRAM, ©2005, pp.812-818. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

16.3 Example: Handling an Attempt to Divide by Zero (Continued)

Demonstrating Exception Handling

The program in Fig. 16.2 uses exception handling to wrap code that might throw a “divide-by-zero” exception and to handle that exception, should one occur. The application enables the user to enter two integers, which are passed as arguments to function quotient (lines 13–21). This function divides the first number (numerator) by the second number (denominator). Assuming that the user does not specify 0 as the denominator for the division, function quotient returns the division result. However, if the user inputs a 0 value as the denominator, function quotient throws an exception. In the sample output, the first two lines show a successful calculation, and the next two lines show a failed calculation due to an attempt to divide by zero. When the exception occurs, the program informs the user of the mistake and prompts the user to input two new integers. After we discuss the code, we will consider the user inputs and flow of program control that yield these outputs.

Enclosing Code in a try Block

The program begins by prompting the user to enter two integers. The integers are input in the condition of the while loop (line 32). After the user inputs values that represent the numerator and denominator, program control proceeds into the loop’s body (lines 33–50). Line 38 passes these values to function quotient (lines 13–21), which either divides the integers and returns a result, or throws an exception (i.e., indicates that an error occurred) on an attempt to divide by zero. Exception handling is geared to situations in which the function that detects an error is unable to handle it.

C++ provides try blocks to enable exception handling. A try block consists of keyword try followed by braces ({}) that define a block of code in which exceptions might occur. The try block encloses statements that might cause exceptions and statements that should be skipped if an exception occurs.

Note that a try block (lines 36–40) encloses the invocation of function quotient and the statement that displays the division result. In this example, because the invocation to function quotient (line 38) can throw an exception, we enclose this function invocation in a try block. Enclosing the output statement (line 39) in the try block ensures that the output will occur only if function quotient returns a result.

Software Engineering Observation
Software Engineering Observation 16.2
Exceptions may surface through explicitly mentioned code in a try block, through calls to other functions and through deeply nested function calls initiated by code in a try block.

Defining a catch Handler to Process a DivideByZeroException

Exceptions are processed by catch handlers (also called exception handlers), which catch and handle exceptions. At least one catch handler (lines 43–47) must immediately follow each try block. Each catch handler begins with the keyword catch and specifies in parentheses an exception parameter that represents the type of exception the catch handler can process (DivideByZeroException in this case). When an exception occurs in a try block, the catch handler that executes is the one whose type matches the type of the exception that occurred (i.e., the type in the catch block matches the thrown exception type exactly or is a base class of it). If an exception parameter includes an optional parameter name, the catch handler can use that parameter name to interact with a caught exception object in the body of the catch handler, which is delimited by braces ({ and }). A catch handler typically reports the error to the user, logs it to a file, terminates the program gracefully or tries an alternate strategy to accomplish the failed task. In this example, the catch handler simply reports that the user attempted to divide by zero. Then the program prompts the user to enter two new integer values.

Common Programming Error
Common Programming Error 16.1
It is a syntax error to place code between a try block and its corresponding catch handlers.
Common Programming Error
Common Programming Error 16.2
Each catch handler can have only a single parameter—specifying a comma-separated list of exception parameters is a syntax error.
Common Programming Error
Common Programming Error 16.3
It is a logic error to catch the same type in two different catch handlers following a single try block.
Additional Pages in this Tutorial: Page 1 | 2 | 3 | 4
Tutorial Index

Google