3.8 Exception Handling

[ Table of Contents ] Prev ] Chapter Overview ] Next ] [ Glossary/Index ]

An exception handler is a section of code used to deal with some exceptional circumstance, such as the onset of an error condition or the arrival of bad data. There are four things to learn regarding exceptions:

The first two are illustrated on the next page. The third and fourth are covered below. (In C++ an exception is "thrown and caught" whereas in Ada it is "raised and handled.") An exception handler, if present, is always the final segment of the executable part of a program unit or block. It follows the reserved word exception and precedes the final end of the program unit or block.

General Form

exception
  when Exception_List_1 =>    -- first handler
    handling_sequence_1;
  when Exception_List_2 =>    -- second handler
    handling_sequence_2;
  -- etc
  when others =>              -- last handler
    handling_sequence_N;
end Unit_Name;

where an Exception_List has the form:

Exception_Name_1 | Exception_Name_2 | ...

Propagation of Exceptions

When an exception is raised (for example, when a numeric quantity goes out of range), control jumps away from the normal executing sequence and an exception handler is sought at the lowest possible level. That is, the runtime system first tries to find an appropriate exception handler in the currently executing block or program unit and if one is found, control goes there. If not, a handler is sought at the next higher level -- in the unit that called the current unit. If an appropriate handler is not found following "propagation of the exception up the call chain" to the main procedure, the program fails. By "appropriate handler" we mean one that contains the Exception_Name corresponding to the actual exceptional event -- such as a predefined exception or an exception declared and raised by the programmer (see example in the next section).

Predefined Exceptions

There are four categories of language-defined exceptions. If one of these occurs, the run-time system will automatically raise the exception. They are:

There are also exceptions declared in the predefined packages outlined in Appendix B.

Example Program with an Exception Handler

Im3-9.gif (4107 bytes)

The program depicted here contains an exception handler inside a block, which is inside a while loop. (A simple rectangle is used as the graphic symbol for each of these constructs.) The handler responds to the situation where the user enters an inappropriate input -- with more than one digit. Rather than have the program crash, the handler notifies the user of the mistake, and the loop gives the user another opportunity to provide a proper input.

A proper input, in this case, is a single-digit integer, as defined in the declaration of the subtype Single_Digit_Type.

Note that the handler illustrated here handles only one category of exception -- called Constraint_Error. If another category (such as one that occurs when the user enters a string of alphabetic characters) is raised, this particular handler would not suffice.

Source Code Listing

------------------------------------------------------------------
--  This program prompts the user to enter a sequence of single-
--  digit integers, and computes their sum. If a value larger than 
--  nine is entered, an exception is raised and handled. 
------------------------------------------------------------------
with Ada.Text_IO, Ada.Integer_Text_IO;
procedure Compute_Sum is
    package Tio renames Ada.Text_IO;
    package Iio renames Ada.Integer_Text_IO;
    
    subtype Single_Digit_Int is Integer range 0..9;
    Component  : Single_Digit_Int;
    Sum        : Natural := 0;
    Finished   : Boolean := False;
begin
    while not Finished loop                       -- start of loop
        begin                                     -- start of block
                
            Tio.Put_Line("Enter 1-digit integer(zero to quit)");
            Iio.Get(Component);
            if Component = 0 then
                Finished := True;
            end if;
            Sum := Sum + Component;
            
        exception                              
            when Constraint_Error =>              -- start of handler
                Tio.Put_Line("Too many digits; try again");
                                                  -- end of handler
        end;                                      -- end of block
    end loop;                                     -- end of loop
    
    Tio.Put("Sum = ");
    Tio.Put(Integer'Image(Sum));
end Compute_Sum;                                           
------------------------------------------------------------------

Here is a sample output from the above program:

     Enter a 1-digit integer (zero to quit)
     4
     Enter a 1-digit integer (zero to quit)
     8
     Enter a 1-digit integer (zero to quit)
     14
     Too many digits; try again
     6
     Enter a 1-digit integer (zero to quit)
     0
     Sum = 18

Note that the block statement does not include a declarative part. This kind of block may be referred to as a "begin-end block" or an "exception-handling block."

Related Topics

2.4 Procedures 2.5 Functions 3.7 Block Statements
3.9 The raise Statement 6.1 Tasks

[ Back to top of pagePrev ] Next ]