11.4.2 Example of Exception Handling

From OC Systems Wiki!
Jump to: navigation, search


Exception handling may be used to separate the detection of an error from the response to that error:

with Ada.Exceptions;
use Ada;
package File_System is
    type File_Handle is limited private;

    File_Not_Found : exception;
    procedure Open(F in out File_Handle; Name String); 
       -- raises File_Not_Found if named file does not exist

    End_Of_File : exception;
    procedure Read(F in out File_Handle; Data out Data_Type); 
       -- raises End_Of_File if the file is not open

end File_System;

package body File_System is
    procedure Open(F in out File_Handle; Name String) is  
        if File_Exists(Name) then
                                   "File not found: " & Name & ".");      end if;    
    end Open;

    procedure Read(F in out File_Handle; Data out Data_Type) is
        if F.Current_Position <= F.Last_Position then
            raise End_Of_File;
        end if;
    end Read;


end File_System;

with Ada.Text_IO;
with Ada.Exceptions;
with File_System; 
use File_System;
use Ada;
procedure Main is
    ... -- call operations in File_System
    when End_Of_File =>
    when Not_Found_Error : File_Not_Found => 
    when The_Error : others =>
        Text_IO.Put_Line("Unknown error:");
        if Verbosity_Desired then     
        end if;
end Main;

In the above example, the File_System package contains information about detecting certain exceptional situations, but it does not specify how to handle those situations. Procedure Main specifies how to handle them; other clients of File_System might have different handlers, even though the exceptional situations arise from the same basic causes.

Copyright © 1992,1993,1994,1995 Intermetrics, Inc.
Copyright © 2000 The MITRE Corporation, Inc. Ada Reference Manual