11.4.1 The Package Exceptions

23
Jan

Static Semantics

1 The following language-defined library package exists: 

2/2

with Ada.Streams;
package Ada.Exceptions is
    pragma Preelaborate(Exceptions);

    type Exception_Id is private;
    pragma Preelaborable_Initialization(Exception_Id);

    Null_Id : constant Exception_Id;
    function Exception_Name(Id : Exception_Id) return String;
    function Wide_Exception_Name(Id : Exception_Id) return Wide_String;
    function Wide_Wide_Exception_Name(Id : Exception_Id)
        return Wide_Wide_String;

3/2

    type Exception_Occurrence is limited private;
    pragma Preelaborable_Initialization(Exception_Occurrence);

    type Exception_Occurrence_Access is access all Exception_Occurrence;
    Null_Occurrence : constant Exception_Occurrence;

4/2

    procedure Raise_Exception(E : in Exception_Id;
                              Message : in String := "");
        pragma No_Return(Raise_Exception);

    function Exception_Message(X : Exception_Occurrence) return String;
    procedure Reraise_Occurrence(X : in Exception_Occurrence);

5/2

    function Exception_Identity(X : Exception_Occurrence)
                                return Exception_Id;
    function Exception_Name(X : Exception_Occurrence) return String;
        -- Same as Exception_Name(Exception_Identity(X)).
    function Wide_Exception_Name(X : Exception_Occurrence)
        return Wide_String;
        -- Same as Wide_Exception_Name(Exception_Identity(X)).
    function Wide_Wide_Exception_Name(X : Exception_Occurrence)
        return Wide_Wide_String;
        -- Same as Wide_Wide_Exception_Name(Exception_Identity(X)).

    function Exception_Information(X : Exception_Occurrence) return String;

6/2

    procedure Save_Occurrence(Target : out Exception_Occurrence;
                              Source : in Exception_Occurrence);
    function Save_Occurrence(Source : Exception_Occurrence)
                             return Exception_Occurrence_Access;

6.1/2

    procedure Read_Exception_Occurrence
       (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
        Item   : out Exception_Occurrence);
    procedure Write_Exception_Occurrence
       (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
        Item : in Exception_Occurrence);

6.2/2

    for Exception_Occurrence'Read use Read_Exception_Occurrence;
    for Exception_Occurrence'Write use Write_Exception_Occurrence;

6.3/2

private
   ... -- not specified by the language
end Ada.Exceptions;

7 Each distinct exception is represented by a distinct value of type Exception_Id. Null_Id does not represent any exception, and is the default initial value of type Exception_Id. Each occurrence of an exception is represented by a value of type Exception_Occurrence. Null_Occurrence does not represent any exception occurrence, and is the default initial value of type Exception_Occurrence.

8/1 For a prefix E that denotes an exception, the following attribute is defined: 

9 E'Identity -- E'Identity returns the unique identity of the exception. The type of this attribute is Exception_Id.

9.a Ramification: In a distributed program, the identity is unique across an entire program, not just across a single partition. Exception propagation works properly across RPC's. An exception can be propagated from one partition to another, and then back to the first, where its identity is known. 

10/2 Raise_Exception raises a new occurrence of the identified exception. In this case Exception_Message returns the Message parameter of Raise_Exception. For a raise_statement with an exception_name, Exception_Message returns implementation-defined information about the exception occurrence. Reraise_Occurrence reraises the specified exception occurrence.

10.1/2 Exception_Message returns the message associated with the given Exception_Occurrence. For an occurrence raised by a call to Raise_Exception, the message is the Message parameter passed to Raise_Exception. For the occurrence raised by a raise_statement with an exception_name and a string_expression, the message is the string_expression. For the occurrence raised by a raise_statement with an exception_name but without a string_expression, the message is a string giving implementation-defined information about the exception occurrence. In all cases, Exception_Message returns a string with lower bound 1. 

10.a Implementation defined: The information returned by Exception_Message.

10.b Ramification: Given an exception E, the raise_statement:

10.c raise E;

10.d is equivalent to this call to Raise_Exception: 

10.e Raise_Exception(E'Identity, Message => implementation-defined-string);

10.e.1/2 Similarly, the raise_statement:

10.e.2/2 raise E with "some information";

10.e.3/2 is equivalent to this call to Raise_Exception: 

10.e.4/2 Raise_Exception(E'Identity, Message => "some information");

10.2/2 Reraise_Occurrence reraises the specified exception occurrence.

10.f Ramification: The following handler: 

10.g

when others =>
    Cleanup;
    raise;

10.h is equivalent to this one: 

10.i

when X : others =>
    Cleanup;
    Reraise_Occurrence(X);

11 Exception_Identity returns the identity of the exception of the occurrence.

12/2 The Wide_Wide_Exception_Name functions return the full expanded name of the exception, in upper case, starting with a root library unit. For an exception declared immediately within package Standard, the defining_identifier is returned. The result is implementation defined if the exception is declared within an unnamed block_statement.

12.a Ramification: See the Implementation Permission below. 

12.b To be honest: This name, as well as each prefix of it, does not denote a renaming_declaration.

12.c/2 Implementation defined: The result of Exceptions. Wide_Wide_Exception_Name for exceptions declared within an unnamed block_statement.

12.d Ramification: Note that we're talking about the name of the exception, not the name of the occurrence. 

12.1/2 The Exception_Name functions (respectively, Wide_Exception_Name) return the same sequence of graphic characters as that defined for Wide_Wide_Exception_Name, if all the graphic characters are defined in Character (respectively, Wide_Character); otherwise, the sequence of characters is implementation defined, but no shorter than that returned by Wide_Wide_Exception_Name for the same value of the argument. 

12.e/2 Implementation defined: The sequence of characters of the value returned by Exceptions.Exception_Name (respectively, Exceptions.Wide_Exception_Name) when some of the graphic characters of Exceptions.Wide_Wide_Exception_Name are not defined in Character (respectively, Wide_Character).

12.2/2 The string returned by the Exception_Name, Wide_Exception_Name, and Wide_Wide_Exception_Name functions has lower bound 1.

13/2 Exception_Information returns implementation-defined information about the exception occurrence. The returned string has lower bound 1. 

13.a Implementation defined: The information returned by Exception_Information.

14/2 Reraise_Occurrence has no effect in the case of Null_Occurrence. {Constraint_Error (raised by failure of run-time check)} Raise_Exception and Exception_Name raise Constraint_Error for a Null_Id. Exception_Message, Exception_Name, and Exception_Information raise Constraint_Error for a Null_Occurrence. Exception_Identity applied to Null_Occurrence returns Null_Id.

14.a.1/2 Ramification: Null_Occurrence can be tested for by comparing Exception_Identity(Occurrence) to Null_Id. 

14.a.2/2 Discussion: Raise_Exception was changed so that it always raises an exception and thus can be a No_Return procedure. A similar change was not made for Reraise_Occurrence, as doing so was determined to be a significant incompatibility. It is not unusual to pass an Exception_Occurrence to other code to delay raising it. If there was no exception, passing Null_Occurrence works fine (nothing is raised). Moreover, as there is no test for Null_Occurrence in Ada 95, this is the only way to write such code without using additional flags. Breaking this sort of code is unacceptable. 

15 The Save_Occurrence procedure copies the Source to the Target. The Save_Occurrence function uses an allocator of type Exception_Occurrence_Access to create a new object, copies the Source to this new object, and returns an access value designating this new object; [the result may be deallocated using an instance of Unchecked_Deallocation.]

15.a Ramification: It's OK to pass Null_Occurrence to the Save_Occurrence subprograms; they don't raise an exception, but simply save the Null_Occurrence. 

15.1/2 Write_Exception_Occurrence writes a representation of an exception occurrence to a stream; Read_Exception_Occurrence reconstructs an exception occurrence from a stream (including one written in a different partition). 

15.b/2 Ramification: This routines are used to define the stream attributes (see 13.13.2) for Exception_Occurrence.

15.c/2 The identity of the exception, as well as the Exception_Name and Exception_Message, have to be preserved across partitions.

15.d/2 The string returned by Exception_Name or Exception_Message on the result of calling the Read attribute on a given stream has to be the same as the value returned by calling the corresponding function on the exception occurrence that was written into the stream with the Write attribute. The string returned by Exception_Information need not be the same, since it is implementation defined anyway. 

15.e/2 Reason: This is important for supporting writing exception occurrences to external files for post-mortem analysis, as well as propagating exceptions across remote subprogram calls in a distributed system (see E.4).

Implementation Permissions

17 An implementation of Exception_Name in a space-constrained environment may return the defining_identifier instead of the full expanded name.

18 The string returned by Exception_Message may be truncated (to no less than 200 characters) by the Save_Occurrence procedure [(not the function)], the Reraise_Occurrence procedure, and the re-raise statement.

18.a Reason: The reason for allowing truncation is to ease implementations. The reason for choosing the number 200 is that this is the minimum source line length that implementations have to support, and this feature seems vaguely related since it's usually a “one-liner”. Note that an implementation is allowed to do this truncation even if it supports arbitrarily long lines. 

Implementation Advice

19 Exception_Message (by default) and Exception_Information should produce information useful for debugging. Exception_Message should be short (about one line), whereas Exception_Information can be long. Exception_Message should not include the Exception_Name. Exception_Information should include both the Exception_Name and the Exception_Message. 

19.a.1/2 Implementation Advice: Exception_Information should provide information useful for debugging, and should include the Exception_Name and Exception_Message.

19.a.2/2 Implementation Advice: Exception_Message by default should be short, provide information useful for debugging, and should not include the Exception_Name.

19.a Reason: It may seem strange to define two subprograms whose semantics is implementation defined. The idea is that a program can print out debugging/error-logging information in a portable way. The program is portable in the sense that it will work in any implementation; it might print out different information, but the presumption is that the information printed out is appropriate for debugging/error analysis on that system. 

19.b Implementation Note: As an example, Exception_Information might include information identifying the location where the exception occurred, and, for predefined exceptions, the specific kind of language-defined check that failed. There is an implementation trade-off here, between how much information is represented in an Exception_Occurrence, and how much can be passed through a re-raise.

19.c The string returned should be in a form suitable for printing to an error log file. This means that it might need to contain line-termination control characters with implementation-defined I/O semantics. The string should neither start nor end with a newline.

19.d If an implementation chooses to provide additional functionality related to exceptions and their occurrences, it should do so by providing one or more children of Ada.Exceptions.

19.e Note that exceptions behave as if declared at library level; there is no “natural scope” for an exception; an exception always exists. Hence, there is no harm in saving an exception occurrence in a data structure, and reraising it later. The reraise has to occur as part of the same program execution, so saving an exception occurrence in a file, reading it back in from a different program execution, and then reraising it is not required to work. This is similar to I/O of access types. Note that it is possible to use RPC to propagate exceptions across partitions.

19.f Here's one way to implement Exception_Occurrence in the private part of the package. Using this method, an implementation need store only the actual number of characters in exception messages. If the user always uses small messages, then exception occurrences can be small. If the user never uses messages, then exception occurrences can be smaller still: 

19.g

type Exception_Occurrence(Message_Length : Natural := 200is
    limited record
        Id : Exception_Id;
        Message : String(1..Message_Length);
    end record;

19.h At the point where an exception is raised, an Exception_Occurrence can be allocated on the stack with exactly the right amount of space for the message — none for an empty message. This is just like declaring a constrained object of the type: 

19.i Temp : Exception_Occurrence(10); -- for a 10-character message

19.j After finding the appropriate handler, the stack can be cut back, and the Temp copied to the right place. This is similar to returning an unknown-sized object from a function. It is not necessary to allocate the maximum possible size for every Exception_Occurrence. If, however, the user declares an Exception_Occurrence object, the discriminant will be permanently set to 200. The Save_Occurrence procedure would then truncate the Exception_Message. Thus, nothing is lost until the user tries to save the occurrence. If the user is willing to pay the cost of heap allocation, the Save_Occurrence function can be used instead.

19.k Note that any arbitrary-sized implementation-defined Exception_Information can be handled in a similar way. For example, if the Exception_Occurrence includes a stack traceback, a discriminant can control the number of stack frames stored. The traceback would be truncated or entirely deleted by the Save_Occurrence procedure — as the implementation sees fit.

19.l If the internal representation involves pointers to data structures that might disappear, it would behoove the implementation to implement it as a controlled type, so that assignment can either copy the data structures or else null out the pointers. Alternatively, if the data structures being pointed at are in a task control block, the implementation could keep a unique sequence number for each task, so it could tell when a task's data structures no longer exist.

19.m Using the above method, heap space is never allocated unless the user calls the Save_Occurrence function.

19.n An alternative implementation would be to store the message strings on the heap when the exception is raised. (It could be the global heap, or it could be a special heap just for this purpose — it doesn't matter.) This representation would be used only for choice parameters. For normal user-defined exception occurrences, the Save_Occurrence procedure would copy the message string into the occurrence itself, truncating as necessary. Thus, in this implementation, Exception_Occurrence would be implemented as a variant record: 

19.o type Exception_Occurrence_Kind is (Normal, As_Choice_Param);

19.p

type Exception_Occurrence(Kind : Exception_Occurrence_Kind := Normal) is
    limited record
        case Kind is
            when Normal =>
                ... -- space for 200 characters
            when As_Choice_Param =>
                ... -- pointer to heap string
        end case;
    end record;

19.q Exception_Occurrences created by the run-time system during exception raising would be As_Choice_Param. User-declared ones would be Normal — the user cannot see the discriminant, and so cannot set it to As_Choice_Param. The strings in the heap would be freed upon completion of the handler.

19.r This alternative implementation corresponds to a heap-based implementation of functions returning unknown-sized results.

19.s One possible implementation of Reraise_Occurrence is as follows: 

19.t

procedure Reraise_Occurrence(X : in Exception_Occurrence) is
begin
    Raise_Exception(Identity(X), Exception_Message(X));
end Reraise_Occurrence;

19.u However, some implementations may wish to retain more information across a re-raise — a stack traceback, for example.

19.v Ramification: Note that Exception_Occurrence is a definite subtype. Hence, values of type Exception_Occurrence may be written to an error log for later analysis, or may be passed to subprograms for immediate error analysis. 

Extensions to Ada 83

19.x {extensions to Ada 83} The Identity attribute of exceptions is new, as is the package Exceptions.

Inconsistencies With Ada 95

19.y/2 {inconsistencies with Ada 95} Amendment Correction: Exception_Identity of an Exception_Occurrence now is defined to return Null_Id for Null_Occurrence, rather than raising Constraint_Error. This provides a simple way to test for Null_Occurrence. We expect that programs that need Constraint_Error raised will be very rare; they can be easily fixed by explicitly testing for Null_Id or by using Exception_Name instead.

19.z/2 Amendment Correction: We now define the lower bound of the string returned from [[Wide_]Wide_]Exception_Name, Exception_Message, and Exception_Information. This makes working with the returned string easier, and is consistent with many other string-returning functions in Ada. This is technically an inconsistency; if a program depended on some other lower bound for the string returned from one of these functions, it could fail when compiled with Ada 2005. Such code is not portable even between Ada 95 implementations, so it should be very rare.

19.aa/2 Amendment Correction: Raise_Exception now raises Constraint_Error if passed Null_Id. This means that it always raises an exception, and thus we can apply pragma No_Return to it. We expect that programs that call Raise_Exception with Null_Id will be rare, and programs that do that and expect no exception to be raised will be rarer; such programs can be easily fixed by explicitly testing for Null_Id before calling Raise_Exception. 

Incompatibilities With Ada 95

19.bb/2 {incompatibilities with Ada 95} Functions Wide_Exception_Name and Wide_Wide_Exception_Name, and procedures Read_Exception_Occurrence and Write_Exception_Occurrence are newly added to Exceptions. If Exceptions is referenced in a use_clause, and an entity E with the same defining_identifier as a new entity in Exceptions is defined in a package that is also referenced in a use_clause, the entity E may no longer be use-visible, resulting in errors. This should be rare and is easily fixed if it does occur. 

Extensions to Ada 95

19.cc/2 {extensions to Ada 95} The package Exceptions is preelaborated, and types Exception_Id and Exception_Occurrence have preelaborable initialization, allowing this package to be used in preelaborated units. 

Wording Changes from Ada 95

19.dd/2 The meaning of Exception_Message is reworded to reflect that the string can come from a raise_statement as well as a call of Raise_Exception.

19.ee/2 Added Wide_Exception_Name and Wide_Wide_Exception_Name because identifiers can now contain characters outside of Latin-1.

[aada]

This package will exist in AAda (it is mandatory to have exceptions anyway!) however, the Raise_Exception procedure will be intrinsic. In other words, it will never be a function call. Instead, the compiler will automatically transform it in a raise E with S; statement.

A brief description of the exception handling in AAda:

As much as possible the exception information will be defined statically. The contact defines a pointer to that static information in order to let the user access it at runtime.

The exception unfolding mechanism requires us to release all the variables from all the blocks of instructions we entered (including declarative blocks!) This is done using a context object which is propagated between functions and procedures. All functions and procedures, upon entry, allocate their own context and initialize it as required. This context contains information of the previous level so we can easily track all the contexts back to the task (linked list) currently maintaining this execution environment.

In effect, whether the user defines an exception handler or not, there is one in each function and procedure that requires it. A function or procedure requires an exception handler when:

a) The compiler statically determined that the code could generate an exception at run time (i.e. the code generated includes constraints checks, possibly even a raise statement);

b) The compiler found a user defined raise statement or an equivalent;

c) Some of the variables need cleanup (i.e. a local access pointer representing a newly allocated object that needs to be deleted before you return, etc.)

Synopsis of an exception being raised:

1. Initialize the exception_id variable in our execution context
2. Go to our exception handler (i.e. opcode: jmp execution_context.exception_ptr;)
3. If a user handler for that exception is found execute it; execute a null; statement otherwise; if the user handling does not reraise the exception, then the exception process is aborted and execution continues at the previous execution level. (i.e. opcode: jmp execution_context.return_ptr)
4. Deallocate all the variables except the return variable if the user handler executed a return (otherwise the return value is not defined anyway)
5. Jump to exception_ptr of the previous level (Jump as in assembly language jmp instruction using the exception handler defined in execution_context.previous_level.exception_ptr.) If there is no previous_level (root) then the exception is dropped (i.e. the task ignore exception except if it is the main task in which case the whole program is aborted.)

The name: exception; declaration creates a function with a pointer. Calling that function initializes the exception_id as required in step 1. Also, that pointer is used to compare the user handled exception and the except that was just raised (i.e. step 3.)

NOTE

(1) Note that each declare block is an execution context in itself, although the code between declare and begin cannot include a user handler (the handler has to be in the previous execution level instead.) Once a declare block was executed, the same execution_context can be reused for the function. At that point, the exception_ptr can be set to the user exception handler of the function.

(2) The exception_ptr within a declare block must be changed after each successful declaration. Any initialization that we know cannot fail will not define an exception pointer. For instance, we may view this as the resulting opcode of the execution of a declare with 3 variables A, B and C.

-- parent function
mov exception_ptr, my_handler
jmp function
-- child function
call init_A
mov exception_ptr, clean_A
call init_B
mov exception_ptr, clean_B
call init_C
mov exception_ptr, clean_C
[...] -- function body
clean_C:
call clean_C
clean_B:
call clean_B
clean_A:
call clean_A
jmp execution_context.return_ptr

Note that this is repeated for all the variables that are automatically initialized within the body. This includes variables defined in a for loop, sub-functions, explicit declare block.

It is not clear, at this point, whether the pointer needs to be very dynamic and whether an out only variable requires special handling. A different approach is to initializes all the variables in two steps:

1) Mark all the variables as not initialized
2) Initialize the variables one by one
3) If an exception occurs in step 2. we can now test whether any one variable was initialized and if so, clean it up

Since exception should not occur, this last approach may actually give us much better results if using an packed Boolean array which is really fast to initialize (i.e. 64 variables can be marked as not initialized in one processor statement [mov [ptr], 0]; whereas, changing the exception pointer each time is 8 bytes each time. So for 64 variables, it would be 8 x 64 bytes to move.)

type execution_context is
  record
    -- first part defined by the caller before calling (and it can be defined ONCE)
    previous_level: access execution_context;
    return_ptr: access back_to_previous_level_label;
    exception_ptr: access back_to_previous_level_label_exception_handler;
    root: access task_environment;
    exception: exception_id;
    calling_parameters: ...;
    -- second part defined by the function or procedure
    return_value: ....; -- not present in procedures
    local_variables: ...;
  end record;

NOTE

(1) The calling_parameters, return_value and local_variables have a variable size given to the caller by the callee. To avoid too many memory allocations, a function will use the largest size necessary for all the calls in itself. That way the buffer is allocated once on entry and doesn't change throughout the entire execution of the very function or procedure.

[/aada]