dwww Home | Show directory contents | Find package


                           Section 11: Exceptions


1   [This section defines the facilities for dealing with errors or other
exceptional situations that arise during program execution.]
{exception occurrence} {condition: See also exception}
{signal (an exception): See raise} {throw (an exception): See raise}
{catch (an exception): See handle} {Exception} [Glossary Entry]An exception
represents a kind of exceptional situation; an occurrence of such a situation
(at run time) is called an exception occurrence. [{raise (an exception)
 [partial]} To raise an exception is to abandon normal program execution so as
to draw attention to the fact that the corresponding situation has arisen.
{handle (an exception) [partial]} Performing some actions in response to the
arising of an exception is called handling the exception. ]

1.a         To be honest: {handle (an exception occurrence) [partial]} ...or
            handling the exception occurrence.

1.b         Ramification: For example, an exception End_Error might represent
            error situations in which an attempt is made to read beyond
            end-of-file. During the execution of a partition, there might be
            numerous occurrences of this exception.

1.c         To be honest: {occurrence (of an exception)} When the meaning is
            clear from the context, we sometimes use "occurrence" as a
            short-hand for "exception occurrence."

2   [An exception_declaration declares a name for an exception. An exception
is raised initially either by a raise_statement or by the failure of a
language-defined check. When an exception arises, control can be transferred
to a user-provided exception_handler at the end of a handled_sequence_of_-
statements, or it can be propagated to a dynamically enclosing execution.]


                         Wording Changes from Ada 83

2.a         We are more explicit about the difference between an exception and
            an occurrence of an exception. This is necessary because we now
            have a type (Exception_Occurrence) that represents exception
            occurrences, so the program can manipulate them. Furthermore, we
            say that when an exception is propagated, it is the same
            occurrence that is being propagated (as opposed to a new
            occurrence of the same exception). The same issue applies to a
            re-raise statement. In order to understand these semantics, we
            have to make this distinction.


11.1 Exception Declarations


1   {exception} An exception_declaration declares a name for an exception.


                                   Syntax

2       exception_declaration ::= defining_identifier_list : exception;


                              Static Semantics

3   Each single exception_declaration declares a name for a different
exception. If a generic unit includes an exception_declaration, the
exception_declarations implicitly generated by different instantiations of the
generic unit refer to distinct exceptions (but all have the same
defining_identifier). The particular exception denoted by an exception name is
determined at compilation time and is the same regardless of how many times
the exception_declaration is elaborated.

3.a         Reason: We considered removing this requirement inside generic
            bodies, because it is an implementation burden for implementations
            that wish to share code among several instances. In the end, it
            was decided that it would introduce too much implementation
            dependence.

3.b         Ramification: Hence, if an exception_declaration occurs in a
            recursive subprogram, the exception name denotes the same
            exception for all invocations of the recursive subprogram. The
            reason for this rule is that we allow an exception occurrence to
            propagate out of its declaration's innermost containing master; if
            exceptions were created by their declarations like other entities,
            they would presumably be destroyed upon leaving the master; we
            would have to do something special to prevent them from
            propagating to places where they no longer exist.

3.c         Ramification: Exception identities are unique across all
            partitions of a program.

4   {predefined exception}
{Constraint_Error (raised by failure of run-time check)}
{Program_Error (raised by failure of run-time check)}
{Storage_Error (raised by failure of run-time check)}
{Tasking_Error (raised by failure of run-time check)} The predefined exceptions
are the ones declared in the declaration of package Standard:
Constraint_Error, Program_Error, Storage_Error, and Tasking_Error[; one of
them is raised when a language-defined check fails.]

4.a         Ramification: The exceptions declared in the language-defined
            package IO_Exceptions, for example, are not predefined.


                              Dynamic Semantics

5   {elaboration (exception_declaration) [partial]} The elaboration of an
exception_declaration has no effect.

6   {Storage_Check [partial]} {check, language-defined (Storage_Check)}
{Storage_Error (raised by failure of run-time check)} The execution of any
construct raises Storage_Error if there is insufficient storage for that
execution. {unspecified [partial]} The amount of storage needed for the
execution of constructs is unspecified.

6.a         Ramification: Note that any execution whatsoever can raise
            Storage_Error. This allows much implementation freedom in storage
            management.


                                  Examples

7   Examples of user-defined exception declarations:

8       Singular : exception;
        Error    : exception;
        Overflow, Underflow : exception;


                         Inconsistencies With Ada 83

8.a         {inconsistencies with Ada 83} The exception Numeric_Error is now
            defined in the Obsolescent features Annex, as a rename of
            Constraint_Error. All checks that raise Numeric_Error in Ada 83
            instead raise Constraint_Error in Ada 95. To increase upward
            compatibility, we also changed the rules to allow the same
            exception to be named more than once by a given handler. Thus, "
            when Constraint_Error | Numeric_Error =>" will remain legal in Ada
            95, even though Constraint_Error and Numeric_Error now denote the
            same exception. However, it will not be legal to have separate
            handlers for Constraint_Error and Numeric_Error. This change is
            inconsistent in the rare case that an existing program explicitly
            raises Numeric_Error at a point where there is a handler for
            Constraint_Error; the exception will now be caught by that
            handler.


                         Wording Changes from Ada 83

8.b         We explicitly define elaboration for exception_declarations.


11.2 Exception Handlers


1   [The response to one or more exceptions is specified by an
exception_handler.]


                                   Syntax

2       handled_sequence_of_statements ::= 
             sequence_of_statements
          [exception
             exception_handler
            {exception_handler}]

3       exception_handler ::= 
          when [choice_parameter_specification:] exception_choice
         {| exception_choice} =>
             sequence_of_statements

4       choice_parameter_specification ::= defining_identifier

5       exception_choice ::= exception_name | others

5.a         To be honest: {handler} "Handler" is an abbreviation for "
            exception_handler."

5.b         {choice (of an exception_handler)} Within this section, we
            sometimes abbreviate "exception_choice" to "choice."


                               Legality Rules

6   {cover (of a choice and an exception)} A choice with an exception_name
covers the named exception. A choice with others covers all exceptions not
named by previous choices of the same handled_sequence_of_statements. Two
choices in different exception_handlers of the same handled_sequence_of_-
statements shall not cover the same exception.

6.a         Ramification: Two exception_choices of the same
            exception_handler may cover the same exception. For example, given
            two renaming declarations in separate packages for the same
            exception, one may nevertheless write, for example, "when
            Ada.Text_IO.Data_Error | My_Seq_IO.Data_Error =>".

6.b         An others choice even covers exceptions that are not visible at
            the place of the handler. Since exception raising is a dynamic
            activity, it is entirely possible for an others handler to handle
            an exception that it could not have named.

7   A choice with others is allowed only for the last handler of a
handled_sequence_of_statements and as the only choice of that handler.

8   An exception_name of a choice shall not denote an exception declared in a
generic formal package.

8.a         Reason: This is because the compiler doesn't know the identity of
            such an exception, and thus can't enforce the coverage rules.


                              Static Semantics

9   {choice parameter} A choice_parameter_specification declares a choice
parameter, which is a constant object of type Exception_Occurrence (see
11.4.1). During the handling of an exception occurrence, the choice parameter,
if any, of the handler represents the exception occurrence that is being
handled.


                              Dynamic Semantics

10  {execution (handled_sequence_of_statements) [partial]} The execution of a
handled_sequence_of_statements consists of the execution of the sequence_of_-
statements. [The optional handlers are used to handle any exceptions that are
propagated by the sequence_of_statements.]


                                  Examples

11  Example of an exception handler:

12      begin
           Open(File, In_File, "input.txt");   -- see A.8.2
        exception
           when E : Name_Error =>
              Put("Cannot open input file : ");
              Put_Line(Exception_Message(E));  -- see 11.4.1
              raise;
        end;


                            Extensions to Ada 83

12.a        {extensions to Ada 83} The syntax rule for exception_handler is
            modified to allow a choice_parameter_specification.

12.b/2      {AI95-00114-01} Different exception_choices of the same
            exception_handler may cover the same exception. This allows for
            "when Numeric_Error | Constraint_Error =>" even though
            Numeric_Error is a rename of Constraint_Error. This also allows
            one to "with" two different I/O packages, and then write, for
            example, "when Ada.Text_IO.Data_Error | My_Seq_IO.Data_Error =>"
            even though these might both be renames of the same exception.


                         Wording Changes from Ada 83

12.c        The syntax rule for handled_sequence_of_statements is new. These
            are now used in all the places where handlers are allowed. This
            obviates the need to explain (in Sections 5, 6, 7, and 9) what
            portions of the program are handled by the handlers. Note that
            there are more such cases in Ada 95.

12.d        The syntax rule for choice_parameter_specification is new.


11.3 Raise Statements


1   [A raise_statement raises an exception.]


                                   Syntax

2/2     {AI95-00361-01} raise_statement ::= raise;
              | raise exception_name [with string_expression];


                               Legality Rules

3   The name, if any, in a raise_statement shall denote an exception.
{re-raise statement} A raise_statement with no exception_name (that is, a
re-raise statement) shall be within a handler, but not within a body enclosed
by that handler.


                            Name Resolution Rules

3.1/2 {AI95-00361-01} The expression, if any, in a raise_statement, is
expected to be of type String.


                              Dynamic Semantics

4/2 {AI95-00361-01} {raise (an exception)} To raise an exception is to raise a
new occurrence of that exception[, as explained in 11.4].
{execution (raise_statement with an exception_name) [partial]} For the
execution of a raise_statement with an exception_name, the named exception is
raised. [If a string_expression is present, the expression is evaluated and
its value is associated with the exception occurrence.]
{execution (re-raise statement) [partial]} For the execution of a re-raise
statement, the exception occurrence that caused transfer of control to the
innermost enclosing handler is raised [again].

4.a.1/2     Proof: {AI95-00361-01} The definition of
            Exceptions.Exception_Message includes a statement that the string
            is returned (see 11.4.1). We describe the use of the string here
            so that we don't have an unexplained parameter in this subclause.

4.a         Implementation Note: For a re-raise statement, the implementation
            does not create a new Exception_Occurrence, but instead propagates
            the same Exception_Occurrence value. This allows the original
            cause of the exception to be determined.


                                  Examples

5   Examples of raise statements:

6/2     {AI95-00433-01} raise Ada.IO_Exceptions.Name_Error;   -- see A.13
        raise Queue_Error with "Buffer Full"; -- see 9.11

7       raise;                                -- re-raise the current exception


                         Wording Changes from Ada 83

7.a         The fact that the name in a raise_statement has to denote an
            exception is not clear from RM83. Clearly that was the intent,
            since the italicized part of the syntax rules so indicate, but
            there was no explicit rule. RM83-1.5(11) doesn't seem to give the
            italicized parts of the syntax any force.


                            Extensions to Ada 95

7.b/2       {AI95-00361-01} {extensions to Ada 95} The syntax of a
            raise_statement is extended to include a string message. This is
            more convenient than calling Exceptions.Exception_Message
            (exception_name'Identity, string_expression), and should encourage
            the use of message strings when raising exceptions.


11.4 Exception Handling


1   [When an exception occurrence is raised, normal program execution is
abandoned and control is transferred to an applicable exception_handler, if
any. {handle (an exception occurrence)} To handle an exception occurrence is
to respond to the exceptional event. {propagate} To propagate an exception
occurrence is to raise it again in another context; that is, to fail to
respond to the exceptional event in the present context.]

1.a         Ramification: In other words, if the execution of a given
            construct raises an exception, but does not handle it, the
            exception is propagated to an enclosing execution (except in the
            case of a task_body).

1.b/1       Propagation involves re-raising the same exception occurrence. For
            example, calling an entry of an uncallable task raises
            Tasking_Error; this is not propagation.


                              Dynamic Semantics

2   {dynamically enclosing (of one execution by another)}
{execution (dynamically enclosing)} Within a given task, if the execution of
construct a is defined by this International Standard to consist (in part) of
the execution of construct b, then while b is executing, the execution of a is
said to dynamically enclose the execution of b.
{innermost dynamically enclosing} The innermost dynamically enclosing execution
of a given execution is the dynamically enclosing execution that started most
recently.

2.a         To be honest: {included (one execution by another)}
            {execution (included by another execution)} If the execution of a
            dynamically encloses that of b, then we also say that the
            execution of b is included in the execution of a.

2.b         Ramification: Examples: The execution of an if_statement
            dynamically encloses the evaluation of the condition after the if
            (during that evaluation). (Recall that "execution" includes both
            "elaboration" and "evaluation", as well as other executions.) The
            evaluation of a function call dynamically encloses the execution
            of the sequence_of_statements of the function body (during that
            execution). Note that, due to recursion, several simultaneous
            executions of the same construct can be occurring at once during
            the execution of a particular task.

2.c         Dynamically enclosing is not defined across task boundaries; a
            task's execution does not include the execution of any other tasks.

2.d         Dynamically enclosing is only defined for executions that are
            occurring at a given moment in time; if an if_statement is
            currently executing the sequence_of_statements after then, then
            the evaluation of the condition is no longer dynamically enclosed
            by the execution of the if_statement (or anything else).

3   {raise (an exception occurrence)} When an exception occurrence is raised
by the execution of a given construct, the rest of the execution of that
construct is abandoned; that is, any portions of the execution that have not
yet taken place are not performed. The construct is first completed, and then
left, as explained in 7.6.1. Then:

4     * If the construct is a task_body, the exception does not propagate
        further;

4.a         Ramification: When an exception is raised by the execution of a
            task_body, there is no dynamically enclosing execution, so the
            exception does not propagate any further. If the exception
            occurred during the activation of the task, then the activator
            raises Tasking_Error, as explained in 9.2, "
            Task Execution - Task Activation", but we don't define that as
            propagation; it's a special rule. Otherwise (the exception
            occurred during the execution of the
            handled_sequence_of_statements of the task), the task silently
            disappears. Thus, abnormal termination of tasks is not always
            considered to be an error.

5     * If the construct is the sequence_of_statements of a
        handled_sequence_of_statements that has a handler with a choice
        covering the exception, the occurrence is handled by that handler;

6     * {propagate (an exception occurrence by an execution, to a dynamically enclosing execution)
        } Otherwise, the occurrence is propagated to the innermost dynamically
        enclosing execution, which means that the occurrence is raised again
        in that context.

6.a         To be honest: {propagate (an exception by an execution)}
            {propagate (an exception by a construct)} As shorthands, we refer
            to the propagation of an exception, and the propagation by a
            construct, if the execution of the construct propagates an
            exception occurrence.

7   {handle (an exception occurrence)} {execution (handler) [partial]}
{elaboration (choice_parameter_specification) [partial]} When an occurrence is
handled by a given handler, the choice_parameter_specification, if any, is
first elaborated, which creates the choice parameter and initializes it to the
occurrence. Then, the sequence_of_statements of the handler is executed; this
execution replaces the abandoned portion of the execution of the
sequence_of_statements.

7.a/2       Ramification: {AI95-00318-02} This "replacement" semantics implies
            that the handler can do pretty much anything the abandoned
            sequence could do; for example, in a function, the handler can
            execute a return statement that applies to the function.

7.b         Ramification: The rules for exceptions raised in library units,
            main subprograms and partitions follow from the normal rules, plus
            the semantics of the environment task described in Section 10 (for
            example, the environment task of a partition elaborates library
            units and calls the main subprogram). If an exception is
            propagated by the main subprogram, it is propagated to the
            environment task, which then terminates abnormally, causing the
            partition to terminate abnormally. Although abnormal termination
            of tasks is not necessarily an error, abnormal termination of a
            partition due to an exception is an error.

        NOTES

8       1  Note that exceptions raised in a declarative_part of a body are not
        handled by the handlers of the handled_sequence_of_statements of that
        body.


11.4.1 The Package Exceptions



                              Static Semantics

1   The following language-defined library package exists:

2/2     {AI95-00362-01} {AI95-00400-01} {AI95-00438-01} 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     {AI95-00362-01}     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     {AI95-00329-01}     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     {AI95-00400-01}     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     {AI95-00438-01}     procedure Save_Occurrence
        (Target : out Exception_Occurrence;
                                      Source : in Exception_Occurrence);
            function Save_Occurrence(Source : Exception_Occurrence)
                                     return Exception_Occurrence_Access;

6.1/2   {AI95-00438-01}     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   {AI95-00438-01}
            for Exception_Occurrence'Read use Read_Exception_Occurrence;
            for Exception_Occurrence'Write use Write_Exception_Occurrence;

6.3/2   {AI95-00438-01} 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 {AI95-00361-01} Raise_Exception raises a new occurrence of the identified
exception.

10.1/2 {AI95-00361-01} {AI95-00378-01} 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    {AI95-00361-01} 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 {AI95-00361-01} 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 {AI95-00400-01} 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 {AI95-00400-01} 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 {AI95-00378-01} {AI95-00417-01} The string returned by the
Exception_Name, Wide_Exception_Name, and Wide_Wide_Exception_Name functions
has lower bound 1.

13/2 {AI95-00378-01} 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 {AI95-00241-01} {AI95-00446-01} 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: {AI95-00241-01} Null_Occurrence can be tested for by
            comparing Exception_Identity(Occurrence) to Null_Id.

14.a.2/2    Discussion: {AI95-00446-01} 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 {AI95-00438-01} 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 Requirements

16/2 This paragraph was deleted.{AI95-00438-01}

16.a/2      This paragraph was deleted.

16.b/2      This paragraph was deleted.

16.c/2      This paragraph was deleted.


                         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 := 200) is
                    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.

19.w/2      This paragraph was deleted.{AI95-00400-01}


                            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      {AI95-00241-01} {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      {AI95-00378-01} {AI95-00417-01} 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     {AI95-00446-01} 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     {AI95-00400-01} {AI95-00438-01} {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     {AI95-00362-01} {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     {AI95-00361-01} 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     {AI95-00400-01} Added Wide_Exception_Name and
            Wide_Wide_Exception_Name because identifiers can now contain
            characters outside of Latin-1.


11.4.2 Pragmas Assert and Assertion_Policy


1/2 {AI95-00286-01} Pragma Assert is used to assert the truth of a Boolean
expression at any point within a sequence of declarations or statements.
Pragma Assertion_Policy is used to control whether such
assertions{Assertions} are to be ignored by the implementation, checked at run-time, or
handled in some implementation-defined manner.


                                   Syntax

2/2     {AI95-00286-01} The form of a pragma Assert is as follows:

3/2       pragma Assert([Check =>] boolean_expression[, [Message =>]
        string_expression]);

4/2     A pragma Assert is allowed at the place where a declarative_item or a
        statement is allowed.

5/2     {AI95-00286-01} The form of a pragma Assertion_Policy is as follows:

6/2       pragma Assertion_Policy(policy_identifier);

7/2     {configuration pragma (Assertion_Policy) [partial]}
        {pragma, configuration (Assertion_Policy) [partial]} A pragma
        Assertion_Policy is a configuration pragma.


                            Name Resolution Rules

8/2 {AI95-00286-01} The expected type for the boolean_expression of a pragma
Assert is any boolean type. The expected type for the string_expression of a
pragma Assert is type String.

8.a/2       Reason: We allow any boolean type to be like if_statements and
            other conditionals; we only allow String for the message in order
            to match raise_statements.


                               Legality Rules

9/2 {AI95-00286-01} The policy_identifier of a pragma Assertion_Policy shall
be either Check, Ignore, or an implementation-defined identifier.

9.a/2       Implementation defined: Implementation-defined policy_identifiers
            allowed in a pragma Assertion_Policy.


                              Static Semantics

10/2 {AI95-00286-01} A pragma Assertion_Policy is a configuration pragma that
specifies the assertion policy in effect for the compilation units to which it
applies. Different policies may apply to different compilation units within
the same partition. The default assertion policy is implementation-defined.

10.a/2      Implementation defined: The default assertion policy.

11/2 {AI95-00286-01} The following language-defined library package exists:

12/2    package Ada.Assertions is
           pragma Pure(Assertions);

13/2       Assertion_Error : exception;

14/2       procedure Assert(Check : in Boolean);
           procedure Assert(Check : in Boolean; Message : in String);

15/2    end Ada.Assertions;

16/2 {AI95-00286-01} A compilation unit containing a pragma Assert has a
semantic dependence on the Assertions library unit.

17/2 {AI95-00286-01} The assertion policy that applies to a generic unit also
applies to all its instances.


                              Dynamic Semantics

18/2 {AI95-00286-01} An assertion policy {assertion policy} specifies how a
pragma Assert is interpreted by the implementation. If the assertion policy is
Ignore at the point of a pragma Assert, the pragma is ignored. If the
assertion policy is Check at the point of a pragma Assert, the elaboration of
the pragma consists of evaluating the boolean expression, and if the result is
False, evaluating the Message argument, if any, and raising the exception
Assertions.Assertion_Error, with a message if the Message argument is provided.

19/2 {AI95-00286-01} Calling the procedure Assertions.Assert without a Message
parameter is equivalent to:

20/2    if Check = False then
           raise Ada.Assertions.Assertion_Error;
        end if;

21/2 {AI95-00286-01} Calling the procedure Assertions.Assert with a Message
parameter is equivalent to:

22/2    if Check = False then
           raise Ada.Assertions.Assertion_Error with Message;
        end if;

23/2 {AI95-00286-01} The procedures Assertions.Assert have these effects
independently of the assertion policy in effect.


                         Implementation Permissions

24/2 {AI95-00286-01} Assertion_Error may be declared by renaming an
implementation-defined exception from another package.

24.a/2      Reason: This permission is intended to allow implementations which
            had an implementation-defined Assert pragma to continue to use
            their originally defined exception. Without this permission, such
            an implementation would be incorrect, as Exception_Name would
            return the wrong name.

25/2 {AI95-00286-01} Implementations may define their own assertion policies.

        NOTES

26/2    2  {AI95-00286-01} Normally, the boolean expression in a pragma Assert
        should not call functions that have significant side-effects when the
        result of the expression is True, so that the particular assertion
        policy in effect will not affect normal operation of the program.


                            Extensions to Ada 95

26.a/2      {AI95-00286-01} {extensions to Ada 95} Pragmas Assert and
            Assertion_Policy, and package Assertions are new.


11.4.3 Example of Exception Handling



                                  Examples

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

2/2     {AI95-00433-01} package File_System is
            type File_Handle is limited private;

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

4           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

5           ...
        end File_System;

6/2     {AI95-00433-01} package body File_System is
            procedure Open(F : in out File_Handle; Name : String) is
            begin
                if File_Exists(Name) then
                    ...
                else
                    raise File_Not_Found with "File not found: " & Name & ".";
                end if;
            end Open;

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

8           ...

9       end File_System;

10      with Ada.Text_IO;
        with Ada.Exceptions;
        with File_System; use File_System;
        use Ada;
        procedure Main is
        begin
            ... -- call operations in File_System
        exception
            when End_Of_File =>
                Close(Some_File);
            when Not_Found_Error : File_Not_Found =>
                Text_IO.Put_Line(Exceptions.Exception_Message(Not_Found_Error));
            when The_Error : others =>
                Text_IO.Put_Line("Unknown error:");
                if Verbosity_Desired then
                    Text_IO.Put_Line(Exceptions.Exception_Information(The_Error));
                else
                    Text_IO.Put_Line(Exceptions.Exception_Name(The_Error));
                    Text_IO.Put_Line(Exceptions.Exception_Message(The_Error));
                end if;
                raise;
        end Main;

11  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.


                         Wording Changes from Ada 83

11.a        The sections labeled "Exceptions Raised During ..." are subsumed
            by this clause, and by parts of Section 9.


11.5 Suppressing Checks


1/2 {AI95-00224-01} Checking pragmas{Checking pragmas} give instructions to an
implementation on handling language-defined checks. A pragma Suppress gives
permission to an implementation to omit certain language-defined checks, while
a pragma Unsuppress revokes the permission to omit checks..

2   {language-defined check} {check (language-defined)}
{run-time check: See language-defined check} {run-time error}
{error (run-time)} A language-defined check (or simply, a "check") is one of
the situations defined by this International Standard that requires a check to
be made at run time to determine whether some condition is true.
{failure (of a language-defined check)} A check fails when the condition being
checked is false, causing an exception to be raised.

2.a         Discussion: All such checks are defined under "
            Dynamic Semantics" in clauses and subclauses throughout the
            standard.


                                   Syntax

3/2     {AI95-00224-01} The forms of checking pragmas are as follows:

4/2     {AI95-00224-01}   pragma Suppress(identifier);

4.1/2   {AI95-00224-01}   pragma Unsuppress(identifier);

5/2     {AI95-00224-01} {configuration pragma (Suppress) [partial]}
        {pragma, configuration (Suppress) [partial]}
        {configuration pragma (Unsuppress) [partial]}
        {pragma, configuration (Unsuppress) [partial]} A checking pragma is
        allowed only immediately within a declarative_part, immediately within
        a package_specification, or as a configuration pragma.


                               Legality Rules

6/2 {AI95-00224-01} The identifier shall be the name of a check.

7/2 This paragraph was deleted.{AI95-00224-01}


                              Static Semantics

7.1/2 {AI95-00224-01} A checking pragma applies to the named check in a
specific region, and applies to all entities in that region. A checking pragma
given in a declarative_part or immediately within a package_specification
applies from the place of the pragma to the end of the innermost enclosing
declarative region. The region for a checking pragma given as a configuration
pragma is the declarative region for the entire compilation unit (or units) to
which it applies.

7.2/2 {AI95-00224-01} If a checking pragma applies to a generic instantiation,
then the checking pragma also applies to the instance. If a checking pragma
applies to a call to a subprogram that has a pragma Inline applied to it, then
the checking pragma also applies to the inlined subprogram body.

8/2 {AI95-00224-01} A pragma Suppress gives permission to an implementation to
omit the named check (or every check in the case of All_Checks) for any
entities to which it applies. {suppressed check} If permission has been given
to suppress a given check, the check is said to be suppressed.

8.a         Ramification: A check is suppressed even if the implementation
            chooses not to actually generate better code.
            {Program_Error (raised by failure of run-time check)} This allows
            the implementation to raise Program_Error, for example, if the
            erroneousness is detected.

8.1/2 {AI95-00224-01} A pragma Unsuppress revokes the permission to omit the
named check (or every check in the case of All_Checks) given by any pragma
Suppress that applies at the point of the pragma Unsuppress. The permission is
revoked for the region to which the pragma Unsuppress applies. If there is no
such permission at the point of a pragma Unsuppress, then the pragma has no
effect. A later pragma Suppress can renew the permission.

9   The following are the language-defined checks:

10    * {Constraint_Error (raised by failure of run-time check)} [The
        following checks correspond to situations in which the exception
        Constraint_Error is raised upon failure.]

11/2    {8652/0036} {AI95-00176-01} {AI95-00231-01} {Access_Check
                     [distributed]} Access_Check
                    [When evaluating a dereference (explicit or implicit),
                    check that the value of the name is not null. When
                    converting to a subtype that excludes null, check that the
                    converted value is not null.]

12      {Discriminant_Check [distributed]} Discriminant_Check
                    [Check that the discriminants of a composite value have
                    the values imposed by a discriminant constraint. Also,
                    when accessing a record component, check that it exists
                    for the current discriminant values.]

13/2    {AI95-00434-01} {Division_Check [distributed]} Division_Check
                    [Check that the second operand is not zero for the
                    operations /, rem and mod.]

14      {Index_Check [distributed]} Index_Check
                    [Check that the bounds of an array value are equal to the
                    corresponding bounds of an index constraint. Also, when
                    accessing a component of an array object, check for each
                    dimension that the given index value belongs to the range
                    defined by the bounds of the array object. Also, when
                    accessing a slice of an array object, check that the given
                    discrete range is compatible with the range defined by the
                    bounds of the array object.]

15      {Length_Check [distributed]} Length_Check
                    [Check that two arrays have matching components, in the
                    case of array subtype conversions, and logical operators
                    for arrays of boolean components.]

16      {Overflow_Check [distributed]} Overflow_Check
                    [Check that a scalar value is within the base range of its
                    type, in cases where the implementation chooses to raise
                    an exception instead of returning the correct mathematical
                    result.]

17      {Range_Check [distributed]} Range_Check
                    [Check that a scalar value satisfies a range constraint.
                    Also, for the elaboration of a subtype_indication, check
                    that the constraint (if present) is compatible with the
                    subtype denoted by the subtype_mark. Also, for an
                    aggregate, check that an index or discriminant value
                    belongs to the corresponding subtype. Also, check that
                    when the result of an operation yields an array, the value
                    of each component belongs to the component subtype.]

18      {Tag_Check [distributed]} Tag_Check
                    [Check that operand tags in a dispatching call are all
                    equal. Check for the correct tag on tagged type
                    conversions, for an assignment_statement, and when
                    returning a tagged limited object from a function.]

19    * {Program_Error (raised by failure of run-time check)} [The following
        checks correspond to situations in which the exception Program_Error
        is raised upon failure.]

19.1/2  {AI95-00280} {Accessibility_Check [distributed]} Accessibility_Check
                    [Check the accessibility level of an entity or view.]

19.2/2  {AI95-00280} {Allocation_Check [distributed]} Allocation_Check
                    [For an allocator, check that the master of any tasks to
                    be created by the allocator is not yet completed or some
                    dependents have not yet terminated, and that the
                    finalization of the collection has not started.]

20      {Elaboration_Check [distributed]} Elaboration_Check
                    [When a subprogram or protected entry is called, a task
                    activation is accomplished, or a generic instantiation is
                    elaborated, check that the body of the corresponding unit
                    has already been elaborated.]

21/2                This paragraph was deleted.{AI95-00280}

22    * [The following check corresponds to situations in which the exception
        Storage_Error is raised upon failure.]

23      {Storage_Check [distributed]}
                    {Storage_Error (raised by failure of run-time check)}
                    Storage_Check
                    [Check that evaluation of an allocator does not require
                    more space than is available for a storage pool. Check
                    that the space available for a task or subprogram has not
                    been exceeded.]

23.a        Reason: We considered splitting this out into three categories:
            Pool_Check (for allocators), Stack_Check (for stack usage), and
            Heap_Check (for implicit use of the heap - use of the heap other
            than through an allocator). Storage_Check would then represent the
            union of these three. However, there seems to be no compelling
            reason to do this, given that it is not feasible to split
            Storage_Error.

24    * [The following check corresponds to all situations in which any
        predefined exception is raised.]

25      {All_Checks [distributed]} All_Checks
                    Represents the union of all checks; [suppressing
                    All_Checks suppresses all checks.]

25.a        Ramification: All_Checks includes both language-defined and
            implementation-defined checks.


                             Erroneous Execution

26  {erroneous execution (cause) [partial]} If a given check has been
suppressed, and the corresponding error situation occurs, the execution of the
program is erroneous.


                         Implementation Permissions

27/2 {AI95-00224-01} An implementation is allowed to place restrictions on
checking pragmas, subject only to the requirement that pragma Unsuppress shall
allow any check names supported by pragma Suppress. An implementation is
allowed to add additional check names, with implementation-defined semantics.
{unspecified [partial]} When Overflow_Check has been suppressed, an
implementation may also suppress an unspecified subset of the Range_Checks.

27.a/2      This paragraph was deleted.{AI95-00224-01}

27.b        Implementation defined: Implementation-defined check names.

27.c        Discussion: For Overflow_Check, the intention is that the
            implementation will suppress any Range_Checks that are implemented
            in the same manner as Overflow_Checks (unless they are free).

27.1/2 {AI95-00224-01} An implementation may support an additional parameter
on pragma Unsuppress similar to the one allowed for pragma Suppress (see
J.10). The meaning of such a parameter is implementation-defined.

27.c.1/2    Implementation defined: Existence and meaning of second parameter
            of pragma Unsuppress.


                            Implementation Advice

28  The implementation should minimize the code executed for checks that have
been suppressed.

28.a.1/2    Implementation Advice: Code executed for checks that have been
            suppressed should be minimized.

28.a        Implementation Note: However, if a given check comes for free (for
            example, the hardware automatically performs the check in parallel
            with doing useful work) or nearly free (for example, the check is
            a tiny portion of an expensive run-time system call), the
            implementation should not bother to suppress the check. Similarly,
            if the implementation detects the failure at compile time and
            provides a warning message, there is no need to actually suppress
            the check.

        NOTES

29      3  {optimization} {efficiency} There is no guarantee that a suppressed
        check is actually removed; hence a pragma Suppress should be used only
        for efficiency reasons.

29.1/2  4  {AI95-00224-01} It is possible to give both a pragma Suppress and
        Unsuppress for the same check immediately within the same
        declarative_part. In that case, the last pragma given determines
        whether or not the check is suppressed. Similarly, it is possible to
        resuppress a check which has been unsuppressed by giving a pragma
        Suppress in an inner declarative region.


                                  Examples

30/2 {AI95-00224-01} Examples of suppressing and unsuppressing checks:

31/2    {AI95-00224-01} pragma Suppress(Index_Check);
        pragma Unsuppress(Overflow_Check);


                            Extensions to Ada 83

31.a        {extensions to Ada 83} A pragma Suppress is allowed as a
            configuration pragma. A pragma Suppress without a name is allowed
            in a package_specification.

31.b        Additional check names are added. We allow implementations to
            define their own checks.


                         Wording Changes from Ada 83

31.c        We define the checks in a distributed manner. Therefore, the long
            list of what checks apply to what is merely a NOTE.

31.d        We have removed the detailed rules about what is allowed in a
            pragma Suppress, and allow implementations to invent their own.
            The RM83 rules weren't quite right, and such a change is necessary
            anyway in the presence of implementation-defined checks.

31.e        We make it clear that the difference between a Range_Check and an
            Overflow_Check is fuzzy. This was true in Ada 83, given RM83-11.6,
            but it was not clear. We considered removing Overflow_Check from
            the language or making it obsolescent, just as we did for
            Numeric_Error. However, we kept it for upward compatibility, and
            because it may be useful on machines where range checking costs
            more than overflow checking, but overflow checking still costs
            something. Different compilers will suppress different checks when
            asked to suppress Overflow_Check - the non-uniformity in this case
            is not harmful, and removing it would have a serious impact on
            optimizers.

31.f        Under Access_Check, dereferences cover the cases of
            selected_component, indexed_component, slice, and attribute that
            are listed in RM83, as well as the new explicit_dereference, which
            was included in selected_component in RM83.


                            Extensions to Ada 95

31.g/2      {AI95-00224-01} {extensions to Ada 95} Pragma Unsuppress is new.

31.h/2      {AI95-00280-01} Allocation_Check was added to support suppressing
            the new check on allocators (see 4.8).


                         Wording Changes from Ada 95

31.i/2      {8652/0036} {AI95-00176-01} {AI95-00224-01} The description of
            Access_Check was corrected by the Corrigendum to include the
            discriminant case. This change was then replaced by the more
            general notion of checking conversions to subtypes that exclude
            null in Ada 2005.

31.j/2      {AI95-00224-01} The On parameter of pragma Suppress was moved to
            Annex J. This feature's effect is inherently non-portable,
            depending on the implementation's model of computation. Compiler
            surveys demonstrated this, showing that implementations vary
            widely in the interpretation of these parameters, even on the same
            target. While this is relatively harmless for Suppress (which is
            never required to do anything), it would be a significant problem
            for Unsuppress (we want the checks to be made for all
            implementations). By moving it, we avoid needing to define the
            meaning of Unsuppress with an On parameter.

31.k/2      {AI95-00280-01} The order of the Program_Error checks was
            corrected to be alphabetical.


11.6 Exceptions and Optimization


1   [{language-defined check} {check (language-defined)} {run-time error}
{error (run-time)} {optimization} {efficiency} This clause gives permission to
the implementation to perform certain "optimizations" that do not necessarily
preserve the canonical semantics.]


                              Dynamic Semantics

2   {canonical semantics} The rest of this International Standard (outside
this clause) defines the canonical semantics of the language. [The canonical
semantics of a given (legal) program determines a set of possible external
effects that can result from the execution of the program with given inputs.]

2.a         Ramification: Note that the canonical semantics is a set of
            possible behaviors, since some reordering, parallelism, and
            non-determinism is allowed by the canonical semantics.

2.b         Discussion: The following parts of the canonical semantics are of
            particular interest to the reader of this clause:

2.c           * Behavior in the presence of abnormal objects and objects with
                invalid representations (see 13.9.1).

2.d           * Various actions that are defined to occur in an arbitrary
                order.

2.e           * Behavior in the presence of a misuse of
                Unchecked_Deallocation, Unchecked_Access, or imported or
                exported entity (see Section 13).

3   [As explained in 1.1.3, "
Conformity of an Implementation with the Standard", the external effect of a
program is defined in terms of its interactions with its external environment.
Hence, the implementation can perform any internal actions whatsoever, in any
order or in parallel, so long as the external effect of the execution of the
program is one that is allowed by the canonical semantics, or by the rules of
this clause.]

3.a         Ramification: Note that an optimization can change the external
            effect of the program, so long as the changed external effect is
            an external effect that is allowed by the semantics. Note that the
            canonical semantics of an erroneous execution allows any external
            effect whatsoever. Hence, if the implementation can prove that
            program execution will be erroneous in certain circumstances,
            there need not be any constraints on the machine code executed in
            those circumstances.


                         Implementation Permissions

4   The following additional permissions are granted to the implementation:

5     * {extra permission to avoid raising exceptions} {undefined result} An
        implementation need not always raise an exception when a
        language-defined check fails. Instead, the operation that failed the
        check can simply yield an undefined result. The exception need be
        raised by the implementation only if, in the absence of raising it,
        the value of this undefined result would have some effect on the
        external interactions of the program. In determining this, the
        implementation shall not presume that an undefined result has a value
        that belongs to its subtype, nor even to the base range of its type,
        if scalar. [Having removed the raise of the exception, the canonical
        semantics will in general allow the implementation to omit the code
        for the check, and some or all of the operation itself.]

5.a         Ramification: Even without this permission, an implementation can
            always remove a check if it cannot possibly fail.

5.b         Reason: We express the permission in terms of removing the raise,
            rather than the operation or the check, as it minimizes the
            disturbance to the canonical semantics (thereby simplifying
            reasoning). By allowing the implementation to omit the raise, it
            thereby does not need to "look" at what happens in the exception
            handler to decide whether the optimization is allowed.

5.c         Discussion: The implementation can also omit checks if they cannot
            possibly fail, or if they could only fail in erroneous executions.
            This follows from the canonical semantics.

5.d         Implementation Note: This permission is intended to allow normal
            "dead code removal" optimizations, even if some of the removed
            code might have failed some language-defined check. However, one
            may not eliminate the raise of an exception if subsequent code
            presumes in some way that the check succeeded. For example:

5.e               if X * Y > Integer'Last then
                      Put_Line("X * Y overflowed");
                  end if;
                exception
                  when others =>
                      Put_Line("X * Y overflowed");

5.e.1       If X*Y does overflow, you may not remove the raise of the
            exception if the code that does the comparison against
            Integer'Last presumes that it is comparing it with an in-range
            Integer value, and hence always yields False.

5.f         As another example where a raise may not be eliminated:

5.g               subtype Str10 is String(1..10);
                  type P10 is access Str10;
                  X : P10 := null;
                begin
                  if X.all'Last = 10 then
                      Put_Line("Oops");
                  end if;

5.g.1       In the above code, it would be wrong to eliminate the raise of
            Constraint_Error on the "X.all" (since X is null), if the code to
            evaluate 'Last always yields 10 by presuming that X.all belongs to
            the subtype Str10, without even "looking."

6     * {extra permission to reorder actions} If an exception is raised due to
        the failure of a language-defined check, then upon reaching the
        corresponding exception_handler (or the termination of the task, if
        none), the external interactions that have occurred need reflect only
        that the exception was raised somewhere within the execution of the
        sequence_of_statements with the handler (or the task_body), possibly
        earlier (or later if the interactions are independent of the result of
        the checked operation) than that defined by the canonical semantics,
        but not within the execution of some abort-deferred operation or
        independent subprogram that does not dynamically enclose the execution
        of the construct whose check failed. {independent subprogram} An
        independent subprogram is one that is defined outside the library unit
        containing the construct whose check failed, and has no Inline
        pragma applied to it. {normal state of an object}
        {abnormal state of an object [partial]} {disruption of an assignment
         [partial]} Any assignment that occurred outside of such
        abort-deferred operations or independent subprograms can be disrupted
        by the raising of the exception, causing the object or its parts to
        become abnormal, and certain subsequent uses of the object to be
        erroneous, as explained in 13.9.1.

6.a         Reason: We allow such variables to become abnormal so that
            assignments (other than to atomic variables) can be disrupted due
            to "imprecise" exceptions or instruction scheduling, and so that
            assignments can be reordered so long as the correct results are
            produced in the end if no language-defined checks fail.

6.b         Ramification: If a check fails, no result dependent on the check
            may be incorporated in an external interaction. In other words,
            there is no permission to output meaningless results due to
            postponing a check.

6.c         Discussion: We believe it is important to state the extra
            permission to reorder actions in terms of what the programmer can
            expect at run time, rather than in terms of what the
            implementation can assume, or what transformations the
            implementation can perform. Otherwise, how can the programmer
            write reliable programs?

6.d         This clause has two conflicting goals: to allow as much
            optimization as possible, and to make program execution as
            predictable as possible (to ease the writing of reliable
            programs). The rules given above represent a compromise.

6.e         Consider the two extremes:

6.f         The extreme conservative rule would be to delete this clause
            entirely. The semantics of Ada would be the canonical semantics.
            This achieves the best predictability. It sounds like a disaster
            from the efficiency point of view, but in practice,
            implementations would provide modes in which less predictability
            but more efficiency would be achieved. Such a mode could even be
            the out-of-the-box mode. In practice, implementers would provide a
            compromise based on their customer's needs. Therefore, we view
            this as one viable alternative.

6.g         The extreme liberal rule would be "the language does not specify
            the execution of a program once a language-defined check has
            failed; such execution can be unpredictable." This achieves the
            best efficiency. It sounds like a disaster from the predictability
            point of view, but in practice it might not be so bad. A user
            would have to assume that exception handlers for exceptions raised
            by language-defined checks are not portable. They would have to
            isolate such code (like all nonportable code), and would have to
            find out, for each implementation of interest, what behaviors can
            be expected. In practice, implementations would tend to avoid
            going so far as to punish their customers too much in terms of
            predictability.

6.h         The most important thing about this clause is that users
            understand what they can expect at run time, and implementers
            understand what optimizations are allowed. Any solution that makes
            this clause contain rules that can interpreted in more than one
            way is unacceptable.

6.i         We have chosen a compromise between the extreme conservative and
            extreme liberal rules. The current rule essentially allows
            arbitrary optimizations within a library unit and inlined
            subprograms reachable from it, but disallow semantics-disrupting
            optimizations across library units in the absence of inlined
            subprograms. This allows a library unit to be debugged, and then
            reused with some confidence that the abstraction it manages cannot
            be broken by bugs outside the library unit.

        NOTES

7       5  The permissions granted by this clause can have an effect on the
        semantics of a program only if the program fails a language-defined
        check.


                         Wording Changes from Ada 83

7.a         RM83-11.6 was unclear. It has been completely rewritten here; we
            hope this version is clearer. Here's what happened to each
            paragraph of RM83-11.6:

7.b           * Paragraphs 1 and 2 contain no semantics; they are merely
                pointing out that anything goes if the canonical semantics is
                preserved. We have similar introductory paragraphs, but we
                have tried to clarify that these are not granting any "
                extra" permission beyond what the rest of the document allows.

7.c           * Paragraphs 3 and 4 are reflected in the "extra permission to
                reorder actions". Note that this permission now allows the
                reordering of assignments in many cases.

7.d           * Paragraph 5 is moved to 4.5, "
                Operators and Expression Evaluation", where operator
                association is discussed. Hence, this is no longer an "extra
                permission" but is part of the canonical semantics.

7.e           * Paragraph 6 now follows from the general permission to store
                out-of-range values for unconstrained subtypes. Note that the
                parameters and results of all the predefined operators of a
                type are of the unconstrained subtype of the type.

7.f           * Paragraph 7 is reflected in the "extra permission to avoid
                raising exceptions".

7.g         We moved clause 11.5, "Suppressing Checks" from after 11.6 to
            before 11.6, in order to preserve the famous number "11.6" (given
            the changes to earlier clauses in Section 11).

Generated by dwww version 1.15 on Sat Jun 15 05:36:05 CEST 2024.