Data Exception with Continuation Example
MC logo
 

Data Exception with Continuation Example

Ada Code Examples


<<Data Exception Example Download Integer Stack with Exceptions>>
--
-- This also uses exceptions to catch data errors, but it uses a begin
-- block with an exception clause to create something like a try block
-- in Java or C++.  This allows it to continue reading after the bad data
-- exception.
--
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure ReadOut3 is
   N: Integer;          -- Number read.
begin
   -- Issue the lovely decoration.
   Put_Line("-----------------------------------------------------" &
            "-----------");

   -- Copy lines, noting bad data and continuing to read.
   loop
      begin
         Get(N);
         Put(N, 1);
         New_Line;
      exception
         when Data_Error =>
            -- This does a text read to show what the input near the error
            -- looks like.
            declare
               S: String(1..40);      -- Portion of input file.
            begin
               Get_Line(S, N);
               Put("Bad data: '");
               Put(S(1..N));
               Put_Line("'");
            end;
      end;
   end loop;

   exception
   when End_Error =>
      -- When reaching end of file, issue the closing lovely decoration and
      -- return from the procedure.
      Put_Line("-----------------------------------------------------" &
               "-----------");
end ReadOut3;
<<Data Exception Example Integer Stack with Exceptions>>