Concepts of Programming Languages

(Sean Pound) #1
14.2 Exception Handling in Ada 641

14.2.5 An Example


The following example program illustrates some simple uses of exception hand-
lers in Ada. The program computes and prints a distribution of input grades by
using an array of counters. The input is a sequence of grades, terminated by a
negative number, which raises a Constraint_Error exception because the
grades are Natural type (nonnegative integers). There are 10 categories of
grades (0–9, 10–19,... , 90–100). The grades themselves are used to compute
indexes into an array of counters, one for each grade category. Invalid input
grades are detected by trapping indexing errors in the counter array. A grade
of 100 is special in the computation of the grade distribution because the cat-
egories all have 10 possible grade values, except the highest, which has 11 (90,
91,... , 100). (The fact that there are more possible A grades than B’s or C’s
is conclusive evidence of the generosity of teachers.) The grade of 100 is also
handled in the same exception handler that is used for invalid input data.

-- Grade Distribution
-- Input: A list of integer values that represent
-- grades, followed by a negative number
-- Output: A distribution of grades, as a percentage for
-- each of the categories 0-9, 10-19,.. .,
-- 90-100.
with Ada.Text_IO, Ada.Integer.Text_IO;
use Ada.Text_IO, Ada.Integer.Text_IO;
procedure Grade_Distribution is
Freq: array (1..10) of Integer := (others => 0);
New_Grade : Natural;
Index,
Limit_1,
Limit_2 : Integer;
begin
Grade_Loop:
loop
begin -- A block for the negative input exception
Get(New_Grade);
exception
when Constraint_Error => -- for negative input
exit Grade_Loop;
end; -- end of negative input block
Index := New_Grade / 10 + 1;
begin -- A block for the subscript range handler
Freq(Index) := Freq(Index) + 1;
exception
-- For index range errors
when Constraint_Error =>
if New_Grade = 100 then
Freq(10) := Freq(10) + 1;
Free download pdf