dwww Home | Show directory contents | Find package


                               11   Exceptions


1/3 {AI05-0299-1} [This clause defines the facilities for dealing with errors
or other exceptional situations that arise during program execution.] An
exception represents a kind of exceptional situation; an occurrence of such a
situation (at run time) is called an exception occurrence. [ To raise an
exception is to abandon normal program execution so as to draw attention to
the fact that the corresponding situation has arisen. Performing some actions
in response to the arising of an exception is called handling the exception. ]

1.a         To be honest: ...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: When the meaning is clear from the context, we
            sometimes use "occurrence" as a short-hand for "exception
            occurrence."

2/3 {AI05-0043-1} {AI05-0258-1} [An exception_declaration declares a name for
an exception. An exception can be raised explicitly (for example, by a
raise_statement) or implicitly (for example, 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.


                        Wording Changes from Ada 2005

2.b/3       {AI05-0043-1} Correction: Generalized the introductory description
            of how an exception can be raised so that it does not appear to
            cover all of the cases.


11.1 Exception Declarations


1   An exception_declaration declares a name for an exception.


                                   Syntax

2/3     {AI05-0183-1} exception_declaration ::= defining_identifier_list
         : exception
           [aspect_specification];


                              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   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   The elaboration of an exception_declaration has no effect.

6   The execution of any construct raises Storage_Error if there is
insufficient storage for that execution. 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         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.


                           Extensions to Ada 2005

8.c/3       {AI05-0183-1} An optional aspect_specification can be used in a
            exception_declaration. This is described in 13.1.1.


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" is an abbreviation for "
            exception_handler."

5.b/3       {AI05-0299-1} Within this clause, we sometimes abbreviate "
            exception_choice" to "choice."


                               Legality Rules

5.1/4 {AI12-0022-1} An exception_name of an exception_choice shall denote an
exception.

6   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   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  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        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 Clauses 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 and Raise Expressions


1   [A raise_statement raises an exception.]


                                   Syntax

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

2.1/4   {AI12-0022-1} {AI12-0152-1} raise_expression ::= 
        raise exception_name [with string_simple_expression]

2.2/4   {AI12-0152-1} If a raise_expression appears within the expression of
        one of the following contexts, the raise_expression shall appear
        within a pair of parentheses within the expression:

2.3/4     * object_declaration;

2.4/4     * modular_type_definition;

2.5/4     * floating_point_definition;

2.6/4     * ordinary_fixed_point_definition;

2.7/4     * decimal_fixed_point_definition;

2.8/4     * default_expression;

2.9/4     * ancestor_part.

2.a.1/4     Reason: Unlike conditional expressions, this doesn't say
            "immediately surrounded"; the only requirement is that it is
            somehow within a pair of parentheses that is part of the
            expression. We need this restriction in order that
            raise_expressions cannot be syntactically confused with
            immediately following constructs (such as aspect_specifications).

2.a.2/4     Discussion: We only need to require that a right parenthesis
            appear somewhere between the raise_expression and the surrounding
            context; that's all we need to specify in order to eliminate the
            ambiguities. Moreover, we don't care at all where the left
            parenthesis is (so long as it is legal, of course).

2.a.3/4     For instance, the following is illegal by this rule:

2.a.4/4         Obj : Boolean := Func_Call or else raise TBD_Error with Atomic;

2.a.5/4     as the "with Atomic" could be part of the raise_expression or part
            of the object declaration. Both of the following are legal:

2.a.6/4         Obj : Boolean := Func_Call or else (raise TBD_Error) with Atomic;
                Obj : Boolean := (Func_Call or else raise TBD_Error) with Atomic;

2.a.7/4     and if the with belongs to the raise_expression, then both of the
            following are legal:

2.a.8/4         Obj : Boolean := Func_Call or else (raise TBD_Error with Atomic);
                Obj : Boolean := (Func_Call or else raise TBD_Error with Atomic);

2.a.9/4     This rule only requires parentheses for raise_expressions that are
            part of the "top-level" of an expression in one of the named
            contexts; the raise_expression is either the entire expression, or
            part of a chain of logical operations. In practice, the
            raise_expression will almost always be last in interesting
            top-level expressions; anything that follows it could never be
            executed, so that should be rare. Other contexts such as
            conditional expressions, qualified expressions, aggregates, and
            even function calls, provide the needed parentheses. All of the
            following are legal, no additional parens are needed:

2.a.10/4        Pre : Boolean  := (if not Is_Valid(Param) then raise Not_Valid_Error);
                A : A_Tagged   := (Some_Tagged'(raise TBD_Error) with Comp => 'A');
                B : Some_Array := (1, 2, 3, others => raise Not_Valid_Error);
                C : Natural    := Func (Val => raise TBD_Error);

2.a.11/4    Parentheses that are part of the context of the expression don't
            count. For instance, the parentheses around the raise_expression
            are required in the following:

2.a.12/4        D : A_Tagged   := ((raise TBD_Error) with Comp => 'A');

2.a.13/4    as ancestor_part is one of the contexts that triggers the rule.

2.a.14/4    This English-language rule could have been implemented instead by
            adding nonterminals initial_expression and initial_relation, which
            are the same as choice_expression and choice_relation except for
            the inclusion of membership in initial_relation. Then,
            initial_expresion could be used in place of expression in all of
            the contexts noted. We did not do that because of the large amount
            of change required, both to the grammar and to language rules that
            refer to the grammar. A complete grammar is given in AI12-0152-1.

2.a.15/4    The use of a raise_expression is illegal in each of
            modular_type_definition, floating_point_definition,
            ordinary_fixed_point_definition, and
            decimal_fixed_point_definition as these uses are required to be
            static and a raise_expression is never static. We include these in
            this rule so that Ada text has an unambiguous syntax in these
            cases.


                               Legality Rules

3/4 {AI12-0022-1} {AI12-0159-1} The exception_name, if any, of a
raise_statement or raise_expression shall denote an exception. 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/4 {AI95-00361-01} {AI12-0022-1} {AI12-0152-1} The string_expression or
string_simple_expression, if any, of a raise_statement or raise_expression is
expected to be of type String.

3.2/4 {AI12-0022-1} {AI12-0159-1} The expected type for a raise_expression
shall be any single type.


                              Dynamic Semantics

4/4 {AI95-00361-01} {AI12-0022-1} {AI12-0152-1} To raise an exception is to
raise a new occurrence of that exception[, as explained in 11.4]. For the
execution of a raise_statement with an exception_name, the named exception is
raised. Similarly, for the evaluation of a raise_expression, the named
exception is raised. [In both of these cases, if a string_expression or
string_simple_expression is present, the expression is evaluated and its value is
associated with the exception occurrence.] 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.

        NOTES

4.1/4   1  {AI12-0062-1} {AI12-0152-1} {AI12-0159-1} If the evaluation of a
        string_expression or string_simple_expression raises an exception,
        that exception is propagated instead of the one denoted by the
        exception_name of the raise_statement or raise_expression.


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


                           Extensions to Ada 2012

7.c/4       {AI12-0022-1} {AI12-0152-1} {AI12-0159-1} Corrigendum: The
            raise_expression is new. This construct is necessary to allow
            conversion of existing specifications to use preconditions and
            predicates without changing the exceptions raised. It is
            considered important enough to be added to Ada 2012 rather than
            waiting for Ada 202x.


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. To handle an exception occurrence is to respond to the exceptional event.
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   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. The innermost dynamically enclosing execution of a given
execution is the dynamically enclosing execution that started most recently.

2.a         To be honest: 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   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     * 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: 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   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 Clause 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       2  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/3     {AI95-00329-01} {AI05-0229-1}     procedure Raise_Exception
        (E : in Exception_Id;
                                      Message : in String := "")
                with No_Return;
            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/4 {AI95-00361-01} {AI95-00378-01} {AI05-0043-1} {AI05-0248-1}
{AI12-0022-1} {AI12-0152-1} 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 or
raise_expression with an exception_name and a string_expression or
string_simple_expression, the message is the string_expression or
string_simple_expression. For the occurrence raised by a raise_statement or
raise_expression with an exception_name but without a string_expression or
string_simple_expression, the message is a string giving
implementation-defined information about the exception occurrence. For an
occurrence originally raised in some other manner (including by the failure of
a language-defined check), the message is an unspecified string. In all cases,
Exception_Message returns a string with lower bound 1.

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

10.a.1/3    Discussion: {AI05-0043-1} There is Implementation Advice about the
            contents of this string for language-defined checks.

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

Paragraph 16 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        The Identity attribute of exceptions is new, as is the package
            Exceptions.


                         Inconsistencies With Ada 95

19.y/2      {AI95-00241-01} 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/3     {AI95-00400-01} {AI95-00438-01} {AI05-0005-1} Functions
            Wide_Exception_Name and Wide_Wide_Exception_Name, and procedures
            Read_Exception_Occurrence and Write_Exception_Occurrence are 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} 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.


                        Wording Changes from Ada 2005

19.ff/3     {AI05-0043-1} Correction: Added explicit wording that the
            exception message for language-defined checks is unspecified. The
            old wording appeared inclusive, but it was not.


11.4.2 Pragmas Assert and Assertion_Policy


1/3 {AI95-00286-01} {AI05-0274-1} Pragma Assert is used to assert the truth of
a boolean expression at a point within a sequence of declarations or
statements.

1.1/3 {AI05-0274-1} Assert pragmas, subtype predicates (see 3.2.4),
preconditions and postconditions (see 6.1.1), and type invariants (see 7.3.2)
are collectively referred to as assertions; their boolean expressions are
referred to as assertion expressions.

1.a.1/3     Glossary entry: A predicate is an assertion that is expected to be
            True for all objects of a given subtype.

1.a.2/3     Glossary entry: A precondition is an assertion that is expected to
            be True when a given subprogram is called.

1.a.3/3     Glossary entry: A postcondition is an assertion that is expected
            to be True when a given subprogram returns normally.

1.a.4/4     Glossary entry: An invariant is an assertion that is expected to
            be True for all objects of a given private type when viewed from
            outside the defining package.

1.a.5/4     Glossary entry: See Invariant.

1.a.6/3     Glossary entry: An assertion is a boolean expression that appears
            in any of the following: a pragma Assert, a predicate, a
            precondition, a postcondition, an invariant, a constraint, or a
            null exclusion. An assertion is expected to be True at run time at
            certain specified places.

1.2/3 {AI05-0274-1} Pragma Assertion_Policy is used to control whether
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);

6.1/3   {AI05-0290-1}   pragma Assertion_Policy(
                 assertion_aspect_mark => policy_identifier
             {, assertion_aspect_mark => policy_identifier});

7/3     {AI05-0290-1} A pragma Assertion_Policy is allowed only immediately
        within a declarative_part, immediately within a
        package_specification, or as 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/3 {AI95-00286-01} {AI05-0290-1} The assertion_aspect_mark of a pragma
Assertion_Policy shall be one of Assert, Static_Predicate, Dynamic_Predicate,
Pre, Pre'Class, Post, Post'Class, Type_Invariant, Type_Invariant'Class, or
some implementation defined aspect_mark. The policy_identifier shall be either
Check, Ignore, or some implementation-defined identifier.

9.a/3       Implementation defined: Implementation-defined policy_identifiers
            and assertion_aspect_marks allowed in a pragma Assertion_Policy.


                              Static Semantics

10/3 {AI95-00286-01} {AI05-0290-1} A pragma Assertion_Policy determines for
each assertion aspect named in the pragma_argument_associations whether
assertions of the given aspect are to be enforced by a run-time check. The
policy_identifier Check requires that assertion expressions of the given
aspect be checked that they evaluate to True at the points specified for the
given aspect; the policy_identifier Ignore requires that the assertion
expression not be evaluated at these points, and the run-time checks not be
performed. [Note that for subtype predicate aspects (see 3.2.4), even when the
applicable Assertion_Policy is Ignore, the predicate will still be evaluated
as part of membership tests and Valid attribute_references, and if static,
will still have an effect on loop iteration over the subtype, and the
selection of case_statement_alternatives and variants.]

10.1/3 {AI05-0290-1} If no assertion_aspect_marks are specified in the pragma,
the specified policy applies to all assertion aspects.

10.2/3 {AI05-0290-1} A pragma Assertion_Policy applies to the named assertion
aspects in a specific region, and applies to all assertion expressions
specified in that region. A pragma Assertion_Policy 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 pragma Assertion_Policy given as a configuration
pragma is the declarative region for the entire compilation unit (or units) to
which it applies.

10.3/3 {AI05-0290-1} If a pragma Assertion_Policy applies to a
generic_instantiation, then the pragma Assertion_Policy applies to the entire
instance.

10.a.1/3    Ramification: This means that an Assertion_Policy pragma that
            occurs in a scope enclosing the declaration of a generic unit but
            not also enclosing the declaration of a given instance of that
            generic unit will not apply to assertion expressions occurring
            within the given instance.

10.4/3 {AI05-0290-1} If multiple Assertion_Policy pragmas apply to a given
construct for a given assertion aspect, the assertion policy is determined by
the one in the innermost enclosing region of a pragma Assertion_Policy
specifying a policy for the assertion aspect. If no such Assertion_Policy
pragma exists, the 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/3 {AI95-00286-01} {AI05-0290-1} A compilation unit containing a check for
an assertion (including a pragma Assert) has a semantic dependence on the
Assertions library unit.

17/3 This paragraph was deleted.{AI95-00286-01} {AI05-0290-1}


                              Dynamic Semantics

18/3 {AI95-00286-01} {AI05-0290-1} If performing checks is required by the
Assert assertion policy in effect at the place 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.


                          Bounded (Run-Time) Errors

23.1/3 {AI05-0274-1} It is a bounded error to invoke a potentially blocking
operation (see 9.5.1) during the evaluation of an assertion expression
associated with a call on, or return from, a protected operation. If the
bounded error is detected, Program_Error is raised. If not detected, execution
proceeds normally, but if it is invoked within a protected action, it might
result in deadlock or a (nested) protected action.


                         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.

26/3 {AI05-0274-1} If the result of a function call in an assertion is not
needed to determine the value of the assertion expression, an implementation
is permitted to omit the function call. [This permission applies even if the
function has side effects.]

27/3 {AI05-0274-1} An implementation need not allow the specification of an
assertion expression if the evaluation of the expression has a side effect
such that an immediate reevaluation of the expression could produce a
different value. Similarly, an implementation need not allow the specification
of an assertion expression that is checked as part of a call on or return from
a callable entity C, if the evaluation of the expression has a side effect
such that the evaluation of some other assertion expression associated with
the same call of (or return from) C could produce a different value than it
would if the first expression had not been evaluated.

27.a/3      Ramification: This allows an implementation to reject such
            assertions. To maximize portability, assertions should not include
            expressions that contain these sorts of side effects.

27.b/3      Discussion: The intended effect of the second part of the rule
            (the part starting with "Similarly") is that an evaluation of the
            involved assertion expressions (subtype predicates, type
            invariants, preconditions and postconditions) in any order yields
            identical results.

27.c/3      The rule is intended to apply to all of the assertion expressions
            that are evaluated at the start of call (and similarly for the
            assertion expressions that are evaluated during the return from a
            call), but not other assertions actually given in the body, nor
            between the assertions checked at the start and end of the call.
            Specifically, a side effect that alters a variable in a function
            called from a precondition expression that changes the result of a
            postcondition expression of the same subprogram does not trigger
            these rules unless it also changes the value of a reevaluation of
            the precondition expression.


                         Language Design Principles

27.d/4      {AI12-0005-1} Our intent is that any assertion expression that
            violates this ImplPerm is considered pathological. We definitely
            want compilers to be able to assume that if you evaluate an
            assertion expression once and it is True, you don't need to
            evaluate it again if all you are doing in the mean time is
            evaluating assertion expressions. We were unable to find wording
            that had this effect that didn't throw out important other cases
            (logging, memo functions), so we settled for a strong warning that
            compilers can reject such pathologies. Perhaps in a future version
            of Ada we'll be able to tighten this up.

        NOTES

28/2    3  {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

28.a/2      {AI95-00286-01} Pragmas Assert and Assertion_Policy, and package
            Assertions are new.


                       Incompatibilities With Ada 2005

28.b/3      {AI05-0274-1} There now is an Implementation Permission to reject
            an assertion expression that calls a function that has a side
            effect such that an immediate reevalution of the expression could
            produce a different value. This means that a pragma Assert that
            works in Ada 2005 might be illegal in Ada 2012 in the unlikely
            event that the compiler detected such an error. This should be
            unlikely to occur in practice and it is considered a good thing,
            as the original expression was tricky and probably was not
            portable (as order of evaluation is unspecified within an
            expression). Moreover, no compiler is required to reject such
            expressions, so there is no need for any compiler to change
            behavior.


                           Extensions to Ada 2005

28.c/3      {AI05-0290-1} Assertion_Policy pragmas are now allowed in more
            places and can specify behavior for individual kinds of
            assertions.


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/3      {AI05-0299-1} The sections labeled "Exceptions Raised During
            ..." are subsumed by this subclause, and by parts of Clause 9.


11.5 Suppressing Checks


1/2 {AI95-00224-01} 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/3 {AI05-0264-1} 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. 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} 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/3 {AI95-00224-01} {AI05-0229-1} {AI05-0290-1} If a checking pragma applies
to a generic_instantiation, then the checking pragma also applies to the
entire instance.

7.a/3       Ramification: {AI05-0290-1} This means that a Suppress pragma that
            occurs in a scope enclosing the declaration of a generic unit but
            not also enclosing the declaration of a given instance of that
            generic unit will not apply to constructs within the given
            instance.

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. 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. 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    * [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
                [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
                [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
                [Check that the second operand is not zero for the operations
                /, rem and mod.]

14      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
                [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
                [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
                [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
                [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    * [The following checks correspond to situations in which the exception
        Program_Error is raised upon failure.]

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

19.2/2  {AI95-00280} 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
                [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
                [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/3    {AI05-0290-1} All_Checks
                Represents the union of all checks; suppressing All_Checks
                suppresses all checks other than those associated with
                assertions. In addition, an implementation is allowed (but not
                required) to behave as if a pragma Assertion_Policy(Ignore)
                applies to any region to which pragma Suppress(All_Checks)
                applies.

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

25.b/3      To be honest: {AI05-0005-1} There are additional checks defined in
            various Specialized Needs Annexes that are not listed here.
            Nevertheless, they are included in All_Checks and named in a
            Suppress pragma on implementations that support the relevant
            annex. Look up "check, language-defined" in the index to find the
            complete list.

25.c/3      Discussion: {AI05-0290-1} We don't want to say that assertions are
            suppressed, because we don't want the potential failure of an
            assertion to cause erroneous execution (see below). Thus they are
            excluded from the suppression part of the above rule and then
            handled with an implicit Ignore policy.


                             Erroneous Execution

26  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.
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      4  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  5  {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        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 nonuniformity 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} 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 (see J.10). This feature's effect is inherently
            nonportable, 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.


                        Wording Changes from Ada 2005

31.l/4      {AI05-0290-1} {AI12-0005-1} The effect of a checking pragma no
            longer applies inside an inlined subprogram body. While this could
            change the behavior of a program that depends on a check being
            suppressed in an inlined body, such a program is erroneous and
            thus no behavior can be depended upon anyway. It's also likely to
            be very rare. We make this change so that inlining has no effect
            on the meaning of the subprogram body (since inlining is never
            required, this is necessary in order to be able to reason about
            the body), and so that assertion policies and suppress work the
            same way for inlining.


11.6 Exceptions and Optimization


1/3 {AI05-0299-1} [ This subclause gives permission to the implementation to
perform certain "optimizations" that do not necessarily preserve the canonical
semantics.]


                              Dynamic Semantics

2/3 {AI05-0299-1} The rest of this International Standard (outside this
subclause) 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
            nondeterminism is allowed by the canonical semantics.

2.b/3       Discussion: {AI05-0299-1} The following parts of the canonical
            semantics are of particular interest to the reader of this
            subclause:

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/3         * {AI05-0299-1} Behavior in the presence of a misuse of
                Unchecked_Deallocation, Unchecked_Access, or imported or
                exported entity (see Clause 13).

3/3 {AI05-0299-1} [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 subclause.]

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     * 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/3   * {AI05-0229-1} 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. An independent subprogram is one
        that is defined outside the library unit containing the construct
        whose check failed, and for which the Inline aspect is False. 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/3       {AI05-0299-1} This subclause 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/3       {AI05-0299-1} The extreme conservative rule would be to delete
            this subclause 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/3       {AI05-0299-1} The most important thing about this subclause is
            that users understand what they can expect at run time, and
            implementers understand what optimizations are allowed. Any
            solution that makes this subclause 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/3     6  {AI05-0299-1} The permissions granted by this subclause 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/3       {AI05-0299-1} We moved subclause 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 subclauses in Clause 11).

Generated by dwww version 1.15 on Sat Jun 15 09:21:25 CEST 2024.