@Part(11, Root="ada.mss")

@Comment{$Date: 2006/10/19 20:44:13 $}
@LabeledSection{Exceptions}

@Comment{$Source: d:\\CvsRoot/ARM/Source/11.MSS,v $}
@Comment{$Revision: 1.64 $}

@begin{Intro}
@redundant[This section defines the facilities for dealing with errors or other
exceptional situations that arise during program execution.]
@Defn{exception occurrence}
@IndexSeeAlso{Term=[condition],See=(exception)}
@IndexSee{Term=[signal (an exception)],See=(raise)}
@IndexSee{Term=[throw (an exception)],See=(raise)}
@IndexSee{Term=[catch (an exception)],See=(handle)}
@ToGlossaryAlso{Term=<Exception>,
  Text=<An @i(exception) represents a kind of exceptional situation;
  an occurrence of such a situation (at run time)
  is called an @i(exception occurrence).
  @redundant[@PDefn2{Term=[raise], Sec=(an exception)}
  To @i{raise} an exception is to abandon normal program execution so
  as to draw attention to the fact that the corresponding situation has
  arisen.
  @PDefn2{Term=[handle], Sec=(an exception)}
  Performing some actions in response to the arising of an exception
  is called @i{handling} the exception.
  ]>}
@begin{Honest}
@PDefn2{Term=[handle], Sec=(an exception occurrence)}
...or handling the exception occurrence.
@end{Honest}
@begin{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.
@end{Ramification}
@begin{Honest}
@Defn{occurrence (of an exception)}
When the meaning is clear from the context,
we sometimes use @lquotes@;@i{occurrence}@rquotes@; as a
short-hand for @lquotes@;exception occurrence.@rquotes@;
@end{Honest}

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

@begin{DiffWord83}
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.
@end{DiffWord83}

@LabeledClause{Exception Declarations}

@begin{Intro}
@Defn{exception}
An @nt{exception_declaration} declares a name for an
exception.
@end{Intro}

@begin{Syntax}
@Syn{lhs=<exception_declaration>,rhs="@Syn2{defining_identifier_list} : @key{exception};"}
@end{Syntax}

@begin{StaticSem}
Each single @nt{exception_declaration} declares a name for a different
exception. If a generic unit includes an @nt{exception_declaration},
the @nt{exception_declaration}s implicitly generated by
different instantiations of the generic unit refer to distinct
exceptions (but all have the same @nt{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
@nt{exception_declaration} is elaborated.
@begin{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.
@end{Reason}
@begin{Ramification}
Hence, if an @nt{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.
@end{Ramification}
@begin{Ramification}
Exception identities are unique across all partitions of a
program.
@end{Ramification}

@Defn{predefined exception}
@Defn2{Term=[Constraint_Error],Sec=(raised by failure of run-time check)}
@Defn2{Term=[Program_Error],Sec=(raised by failure of run-time check)}
@Defn2{Term=[Storage_Error],Sec=(raised by failure of run-time check)}
@Defn2{Term=[Tasking_Error],Sec=(raised by failure of run-time check)}
The @i{predefined} exceptions are the ones declared in the
declaration of package Standard:
Constraint_Error, Program_Error,
Storage_Error, and Tasking_Error@Redundant[;
one of them is raised when a language-defined check fails.]
@begin{Ramification}
The exceptions declared in the
language-defined package IO_Exceptions, for example,
are not predefined.
@end{Ramification}
@end{StaticSem}

@begin{RunTime}
@PDefn2{Term=[elaboration], Sec=(exception_declaration)}
The elaboration of an @nt{exception_declaration} has no effect.

@IndexCheck{Storage_Check}
@Defn2{Term=[Storage_Error],Sec=(raised by failure of run-time check)}
The execution of any construct raises Storage_Error if there is
insufficient storage for that execution.
@PDefn{unspecified}
The amount of storage needed for the execution of constructs is
unspecified.
@begin{Ramification}
Note that any execution whatsoever can raise Storage_Error.
This allows much implementation freedom in storage management.
@end{Ramification}
@end{RunTime}

@begin{Examples}
@leading@keepnext@i{Examples of user-defined exception declarations:}
@begin{Example}
Singular : @key[exception];
Error    : @key[exception];
Overflow, Underflow : @key[exception];
@end{Example}
@end{Examples}

@begin{Inconsistent83}
@Defn{inconsistencies with Ada 83}
The exception Numeric_Error is now defined in the Obsolescent
features Annex, as a rename of Constraint_Error.
All checks that raise Numeric_Error in Ada 83
instead raise Constraint_Error in Ada 95.
To increase upward compatibility,
we also changed the rules to allow the same exception to be named
more than once by a given handler.
Thus,
@lquotes@;@key[when] Constraint_Error | Numeric_Error =>@rquotes@; 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.
@end{Inconsistent83}

@begin{DiffWord83}
We explicitly define elaboration for @nt{exception_declaration}s.
@end{DiffWord83}

@LabeledClause{Exception Handlers}

@begin{Intro}
@redundant[The response to one or more exceptions is specified by an
@nt{exception_handler}.]
@end{Intro}

@begin{Syntax}
@Syn{lhs=<handled_sequence_of_statements>,rhs="
     @Syn2{sequence_of_statements}
  [@key{exception}
     @Syn2{exception_handler}
    {@Syn2{exception_handler}}]"}


@Syn{lhs=<exception_handler>,rhs="
  @key{when} [@Syn2{choice_parameter_specification}:] @Syn2{exception_choice} {| @Syn2{exception_choice}} =>
     @Syn2{sequence_of_statements}"}

@Syn{lhs=<choice_parameter_specification>,rhs="@Syn2{defining_identifier}"}

@Syn{lhs=<exception_choice>,rhs="@SynI{exception_}@Syn2{name} | @key{others}"}
@begin{Honest}
@Defn{handler}
@lquotes@;@i{Handler}@rquotes@; is an abbreviation for @lquotes@;@nt{exception_handler}.@rquotes@;

@Defn2{term=<choice>, Sec=<of an @nt{exception_handler}>}
Within this section, we sometimes abbreviate
@lquotes@;@nt{exception_choice}@rquotes@; to @lquotes@;@i{choice}.@rquotes@;
@end{Honest}
@end{Syntax}

@begin{Legality}
@Defn2{term=<cover>, Sec=<of a choice and an exception>}
A choice with an
@SynI{exception_}@nt{name} @i{covers} the named exception.
A choice with @key{others} covers all exceptions
not named by previous choices of the same
@nt{handled_@!sequence_of_@!statements}.
Two choices in different @nt<exception_handler>s of the same
@nt{handled_@!sequence_of_@!statements} shall not cover the same
exception.
@begin{Ramification}
  Two @nt<exception_choice>s of the same @nt<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,
  @lquotes@;@key[when] Ada.Text_IO.Data_Error | My_Seq_IO.Data_Error =>@rquotes@;.

  An @key{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 @key{others} handler to handle an
  exception that it could not have named.
@end{Ramification}

A choice with @key{others} is allowed only for the
last handler of a @nt{handled_sequence_of_statements}
and as the only choice of that handler.

An @SynI{exception_}@nt{name} of a choice shall not denote an
exception declared in a generic formal package.
@begin{Reason}
This is because the compiler doesn't know the identity of such an
exception, and thus can't enforce the coverage rules.
@end{Reason}
@end{Legality}

@begin{StaticSem}
@Defn{choice parameter}
A @nt{choice_parameter_specification} declares a
@i{choice parameter}, which is a constant object of type
Exception_Occurrence (see @RefSecNum{The Package Exceptions}).
During the handling of an exception occurrence,
the choice parameter, if any, of the handler
represents the exception occurrence that is being handled.

@end{StaticSem}

@begin{RunTime}
@PDefn2{Term=[execution], Sec=(handled_sequence_of_statements)}
The execution of a @nt<handled_sequence_of_statements> consists
of the execution of the @nt<sequence_of_@!statements>.
@Redundant[The optional handlers are used to handle any exceptions
that are propagated by the @nt{sequence_of_@!statements}.]
@end{RunTime}

@begin{Examples}
@leading@keepnext@i{Example of an exception handler:}
@begin{Example}
@key[begin]
   Open(File, In_File, "input.txt");   --@RI[ see @RefSecNum{File Management}]
@key[exception]
   @key[when] E : Name_Error =>
      Put("Cannot open input file : ");
      Put_Line(Exception_Message(E));  --@RI[ see @RefSecNum{The Package Exceptions}]
      @key[raise];
@key[end];
@end{Example}
@end{Examples}

@begin{Extend83}
@Defn{extensions to Ada 83}
The syntax rule for @nt{exception_handler} is modified to
allow a @nt{choice_parameter_specification}.

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00114-01]}
Different @Chg{Version=[2],New=[@nt{exception_choice}s],Old=[@ntf<choice>s]}
of the same @nt<exception_handler> may
cover the same exception. This allows for
@lquotes@;when Numeric_Error | Constraint_Error =>@rquotes@; even though
Numeric_Error is a rename of Constraint_Error.
This also allows one to @lquotes@;with@rquotes@; two different I/O packages,
and then write, for example,
@lquotes@;when Ada.Text_IO.Data_Error | My_Seq_IO.Data_Error =>@rquotes@;
even though these might both be renames of the same exception.
@end{Extend83}

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

The syntax rule for @nt{choice_parameter_specification} is new.
@end{DiffWord83}

@LabeledClause{Raise Statements}

@begin{Intro}
@redundant[A @nt{raise_statement} raises an exception.]
@end{Intro}

@begin{Syntax}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00361-01]}
@Syn{lhs=<raise_statement>,rhs="@Chg{Version=[2],New=<@key{raise};
      | @key{raise} @SynI{exception_}@Syn2{name} [@key{with} @SynI{string_}@Syn2{expression}];>,
Old=<@key{raise} [@SynI{exception_}@Syn2{name}];>}"}
@end{Syntax}

@begin{Legality}
The @nt{name}, if any, in a @nt{raise_statement} shall denote
an exception.
@Defn{re-raise statement}
A @nt{raise_statement} with no @SynI{exception_}@nt{name}
(that is, a @i{re-raise statement})
shall be within a handler,
but not within a body enclosed by that handler.
@end{Legality}

@begin{Resolution}
@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00361-01]}
@ChgAdded{Version=[2],Text=[The @nt<expression>, if any, in a
@nt<raise_statement>, is expected to be of type String.]}
@end{Resolution}

@begin{RunTime}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00361-01]}
@Defn2{Term=[raise], Sec=(an exception)}
To @i(raise an exception) is to
raise a new occurrence of that exception@Redundant[,
as explained in @RefSecNum{Exception Handling}].
@PDefn2{Term=[execution], Sec=(raise_statement with an exception_name)}
For the execution of a @nt{raise_statement} with an
@SynI{exception_}@nt{name}, the named exception is raised.
@Chg{Version=[2],New=[@redundant{If a @SynI<string_>@nt<expression> is present,
the @nt{expression} is evaluated and its value is associated with the
exception occurrence.}],Old=[]}
@PDefn2{Term=[execution], Sec=(re-raise statement)}
For the execution of a re-raise statement,
the exception occurrence that caused transfer of control to the
innermost enclosing handler is raised @Redundant[again].
@begin{TheProof}
@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00361-01]}
@ChgAdded{Version=[2],Text=[The definition of Exceptions.Exception_Message
includes a statement that the string is returned (see
@RefSecNum{The Package Exceptions}). We describe the use of the string
here so that we don't have an unexplained parameter in this subclause.]}
@end{TheProof}
@begin{ImplNote}
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.
@end{ImplNote}
@end{RunTime}

@begin{Examples}
@leading@keepnext@i{Examples of raise statements:}
@begin{Example}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00433-01]}
@key[raise] Ada.IO_Exceptions.Name_Error;   --@RI[ see @RefSecNum{Exceptions In Input-Output}]@Chg{Version=[2],New=[
@key[raise] Queue_Error @key[with] "Buffer Full"; --@RI[ see @RefSecNum{Example of Tasking and Synchronization}]],Old=[]}

@key[raise];                                --@RI[ re-raise the current exception]
@end{Example}
@end{Examples}

@begin{DiffWord83}
The fact that the @nt{name} in a @nt{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.
@end{DiffWord83}

@begin{Extend95}
  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00361-01]}
  @ChgAdded{Version=[2],Text=[@Defn{extensions to Ada 95}The syntax of a
  @nt{raise_statement} is extended to include a string message. This is more
  convenient than calling Exceptions.Exception_Message
  (@SynI{exception_}@nt{name}'Identity, @SynI{string_}@nt{expression}), and
  should encourage the use of message strings when raising exceptions.]}
@end{Extend95}


@LabeledClause{Exception Handling}

@begin{Intro}
@redundant[When an exception occurrence is raised,
normal program execution is abandoned
and control is transferred to an applicable @nt{exception_handler},
if any.
@Defn2{Term=[handle], Sec=(an exception occurrence)}
To @i(handle) an exception occurrence is to respond to the
exceptional event.
@Defn{propagate}
To @i(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.]
@begin{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 @nt{task_body}).

@ChgRef{Version=[1],Kind=[Revised]}@ChgNote{Presentation AI-00023}
Propagation involves re-raising the same exception occurrence@Chg{New=[],
Old=[(assuming the implementation has not taken advantage of the
@ImplPermName of @RefSecNum{Raise Statements})]}.
For example, calling an entry of an uncallable task raises
Tasking_Error; this is not propagation.
@end{Ramification}
@end{Intro}

@begin{RunTime}
@Defn2{Term=[dynamically enclosing], Sec=(of one execution by another)}
@Defn2{Term=[execution], Sec=(dynamically enclosing)}
Within a given task, if the
execution of construct @i{a} is defined by this International Standard
to consist (in part) of the
execution of construct @i{b}, then while @i{b} is executing, the
execution of @i{a} is said to @i(dynamically enclose) the execution of
@i{b}.
@Defn{innermost dynamically enclosing}
The @i(innermost
dynamically enclosing) execution of a given execution is the
dynamically enclosing execution that started most recently.
@begin{Honest}
@Defn2{Term=[included], Sec=(one execution by another)}
@Defn2{Term=[execution], Sec=(included by another execution)}
If the execution of @i{a} dynamically encloses that of @i{b},
then we also say that the execution of @i{b} is
@i{included in} the execution of @i{a}.
@end{Honest}
@begin{Ramification}
Examples: The execution of an @nt{if_statement}
dynamically encloses the evaluation of the @nt{condition} after the
@key{if} (during that evaluation).
(Recall that @lquotes@;execution@rquotes@; includes both @lquotes@;elaboration@rquotes@; and
@lquotes@;evaluation@rquotes@;, as well as other executions.)
The evaluation of a function call dynamically encloses the execution
of the @nt{sequence_of_statements} of the function @nt{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.

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

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

@Leading@Defn2{Term=[raise], Sec=(an exception occurrence)}
When an exception occurrence is raised by the execution of a given
construct, the rest of the execution of that construct is @i{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 @RefSecNum{Completion and Finalization}.
Then:
@begin{Itemize}
If the construct is a @nt<task_body>,
the exception does not propagate further;
@begin{Ramification}
  When an exception is raised by the execution of a
  @nt{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 @RefSec{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
  @nt{handled_sequence_of_statements} of the task),
  the task silently disappears.
  Thus, abnormal termination of tasks is not always considered to be an
  error.
@end{Ramification}

If the construct is the @nt{sequence_of_statements} of a
@nt{handled_sequence_of_statements} that has a
handler with a choice covering the exception,
the occurrence is handled by that handler;

@Defn2{Term=[propagate],
Sec=(an exception occurrence by an execution, to a dynamically enclosing execution)}
Otherwise, the occurrence is @i{propagated}
to the innermost dynamically enclosing execution,
which means that the occurrence is raised again
in that context.
@begin{Honest}
@Defn2{Term=[propagate], Sec=(an exception by an execution)}
@Defn2{Term=[propagate], Sec=(an exception by a construct)}
As shorthands, we refer to the @i{propagation of an exception},
and the @i{propagation by a construct},
if the execution of the construct propagates an exception occurrence.
@end{Honest}
@end{Itemize}

@Defn2{Term=[handle], Sec=(an exception occurrence)}
@PDefn2{Term=[execution], Sec=(handler)}
@PDefn2{Term=[elaboration], Sec=(choice_parameter_specification)}
When an occurrence is @i(handled) by a given handler,
the @nt{choice_parameter_specification}, if any, is first elaborated,
which creates the choice parameter and initializes it to the occurrence.
Then, the @nt{sequence_of_statements} of the
handler is executed;
this execution replaces the abandoned portion of the execution of
the @nt{sequence_of_statements}.
@begin{Ramification}
  @ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00318-02]}
  This @lquotes@;replacement@rquotes@; 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 @Chg{Version=[2],New=[return statement],
  Old=[@nt{return_statement}]} that applies to the function.
@end{Ramification}
@begin{Ramification}
The rules for exceptions raised in library units,
main subprograms and partitions follow from the normal rules,
plus the semantics of the environment task
described in Section 10 (for example, the
environment task of a partition elaborates library units and calls
the main subprogram).
If an exception is propagated by the main subprogram, it is
propagated to the environment task, which then terminates abnormally,
causing the partition to terminate abnormally.
Although abnormal termination of tasks is not necessarily an error,
abnormal termination of a partition due to an exception @i{is} an
error.
@end{Ramification}
@end{RunTime}

@begin{Notes}
Note that exceptions raised in a @nt{declarative_part} of a body
are not handled by the handlers of the
@nt{handled_@!sequence_of_@!statements} of that body.
@end{Notes}

@LabeledSubClause{The Package Exceptions}

@begin{StaticSem}
@leading@keepnext@;The following language-defined library package exists:
@begin{Example}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00362-01],ARef=[AI95-00400-01],ARef=[AI95-00438-01]}
@ChildUnit{Parent=[Ada],Child=[Exceptions]}@Chg{Version=[2],New=[@key[with] Ada.Streams;
],Old=[]}@key[package] Ada.Exceptions @key[is]@Chg{Version=[2],New=[
    @key[pragma] Preelaborate(Exceptions);],Old=[]}
    @key[type] @AdaTypeDefn{Exception_Id} @key[is] @key[private];@Chg{Version=[2],New=[
    @key[pragma] Preelaborable_Initialization(Exception_Id);],Old=[]}
    @AdaObjDefn{Null_Id} : @key[constant] Exception_Id;
    @key[function] @AdaSubDefn{Exception_Name}(Id : Exception_Id) @key[return] String;@Chg{Version=[2],New=[
    @key[function] @AdaSubDefn{Wide_Exception_Name}(Id : Exception_Id) @key[return] Wide_String;
    @key[function] @AdaSubDefn{Wide_Wide_Exception_Name}(Id : Exception_Id)
        @key[return] Wide_Wide_String;],Old=[]}

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00362-01]}
    @key[type] @AdaTypeDefn{Exception_Occurrence} @key[is] @key[limited] @key[private];@Chg{Version=[2],New=[
    @key[pragma] Preelaborable_Initialization(Exception_Occurrence);],Old=[]}
    @key[type] @AdaTypeDefn{Exception_Occurrence_Access} @key[is] @key[access] @key[all] Exception_Occurrence;
    @AdaObjDefn{Null_Occurrence} : @key[constant] Exception_Occurrence;

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00329-01]}
    @key[procedure] @AdaSubDefn{Raise_Exception}(E : @key[in] Exception_Id;
                              Message : @key[in] String := "");@Chg{Version=[2],New=[
        @key[pragma] No_Return(Raise_Exception);],Old=[]}
    @key[function] @AdaSubDefn{Exception_Message}(X : Exception_Occurrence) @key[return] String;
    @key[procedure] @AdaSubDefn{Reraise_Occurrence}(X : @key[in] Exception_Occurrence);

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00400-01]}
    @key[function] @AdaSubDefn{Exception_Identity}(X : Exception_Occurrence)
                                @key[return] Exception_Id;
    @key[function] @AdaSubDefn{Exception_Name}(X : Exception_Occurrence) @key[return] String;
        --@RI{ Same as Exception_Name(Exception_Identity(X)).}@Chg{Version=[2],New=[
    @key[function] @AdaSubDefn{Wide_Exception_Name}(X : Exception_Occurrence)
        @key[return] Wide_String;
        --@RI{ Same as Wide_Exception_Name(Exception_Identity(X)).}
    @key[function] @AdaSubDefn{Wide_Wide_Exception_Name}(X : Exception_Occurrence)
        @key[return] Wide_Wide_String;
        --@RI{ Same as Wide_Wide_Exception_Name(Exception_Identity(X)).}],Old=[]}
    @key[function] @AdaSubDefn{Exception_Information}(X : Exception_Occurrence) @key[return] String;

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00438-01]}
    @key[procedure] @AdaSubDefn{Save_Occurrence}(Target : @key[out] Exception_Occurrence;
                              Source : @key[in] Exception_Occurrence);
    @key[function] @AdaSubDefn{Save_Occurrence}(Source : Exception_Occurrence)
                             @key[return] Exception_Occurrence_Access;@Chg{Version=[2],New=[],Old=[
@key[private]
   ... --@RI{ not specified by the language}
@key[end] Ada.Exceptions;]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00438-01]}
@ChgAdded{Version=[2],Text=[    @key[procedure] Read_Exception_Occurrence
       (Stream : @key[not null access] Ada.Streams.Root_Stream_Type'Class;
        Item   : @key[out] Exception_Occurrence);
    @key[procedure] Write_Exception_Occurrence
       (Stream : @key[not null access] Ada.Streams.Root_Stream_Type'Class;
        Item   : @key[in] Exception_Occurrence);]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00438-01]}
@ChgAdded{Version=[2],Text=[    @key[for] Exception_Occurrence'Read @key[use] Read_Exception_Occurrence;
    @key[for] Exception_Occurrence'Write @key[use] Write_Exception_Occurrence;]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00438-01]}
@ChgAdded{Version=[2],Text=[@key[private]
   ... --@RI{ not specified by the language}
@key[end] Ada.Exceptions;]}
@end{Example}

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.

@ChgRef{Version=[1],Kind=[Revised]}@ChgNote{To be consistent with 8652/0006}
@Leading@;For @ChgPrefixType{Version=[1],Kind=[Revised],Text=[a
@Chg{New=[@nt{prefix}],Old=[prefix]} E that denotes an exception]},
the following attribute is defined:
@begin{Description}
@Attribute{Prefix=<E>, AttrName=<Identity>,
  Text=[E'Identity returns the unique identity of the exception.
        The type of this attribute is Exception_Id.]}
@begin{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.
@end{Ramification}
@end{Description}

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00361-01]}
Raise_Exception raises a new occurrence of the identified
exception.@Chg{Version=[2],New=[],Old=[ In this case
Exception_Message returns the Message parameter of Raise_Exception.
For a @nt{raise_statement} with an @i{exception_}@nt{name},
Exception_Message returns implementation-defined information
about the exception occurrence.
Reraise_Occurrence reraises the specified exception occurrence.]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00361-01],ARef=[AI95-00378-01]}
@ChgAdded{Version=[2],Text=[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 @nt{raise_statement} with an
@SynI{exception_}@nt{name} and a @SynI{string_}@nt{expression}, the message is
the @Syni{string_}@nt{expression}. For the occurrence raised by a
@nt{raise_statement} with
an @Syni{exception_}@nt{name} but without a @Syni{string_}@nt{expression},
the message is a string giving implementation-defined information about the
exception occurrence. In all cases, Exception_Message returns a string with
lower bound 1.]}
@ImplDef{The information returned by Exception_Message.}

@begin{Ramification}
@Leading@Keepnext@;Given an exception E, the @nt{raise_statement}:
@begin{Example}
@key[raise] E;
@end{Example}

@Leading@keepnext@;is equivalent to this call to Raise_Exception:
@begin{Example}
Raise_Exception(E'Identity, Message => @RI{implementation-defined-string});
@end{Example}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00361-01]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[Similarly, the
@nt{raise_statement}:]}
@begin{Example}
@ChgRef{Version=[2],Kind=[Added]}
@ChgAdded{Version=[2],Text=[@key[raise] E @key[with] "some information";]}
@end{Example}

@ChgRef{Version=[2],Kind=[Added]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[is equivalent to
this call to Raise_Exception:]}
@begin{Example}
@ChgRef{Version=[2],Kind=[Added]}
@ChgAdded{Version=[2],Text=[Raise_Exception(E'Identity, Message => "some information");]}
@end{Example}
@end{Ramification}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00361-01]}
@ChgAdded{Version=[2],Text=[Reraise_Occurrence reraises the specified exception
occurrence.]}

@begin{Ramification}
@Leading@keepnext@;The following handler:
@begin{Example}
@key[when] @key[others] =>
    Cleanup;
    @key[raise];
@end{Example}

@begin{Wide}
@Leading@keepnext@;is equivalent to this one:
@end{Wide}
@begin{Example}
@key[when] X : @key[others] =>
    Cleanup;
    Reraise_Occurrence(X);
@end{Example}

@end{Ramification}

Exception_Identity returns the identity of the exception of the
occurrence.

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00400-01]}
The @Chg{Version=[2],New=[Wide_@!Wide_@!Exception_Name],Old=[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 @nt{defining_@!identifier} is returned.
The result is implementation defined if the exception is declared within
an unnamed @nt{block_statement}.
@begin{Ramification}
  See the @ImplPermName below.
@end{Ramification}
@begin{Honest}
  This name, as well as each @nt{prefix} of it,
  does not denote a @nt{renaming_declaration}.
@end{Honest}
@ChgImplDef{Version=[2],Kind=[Revised],Text=[The result of @Chg{Version=[2],
New=[Exceptions.@!Wide_@!Wide_@!Exception_@!Name],Old=[Exceptions.@!Exception_@!Name]}
for @Chg{Version=[2],New=[exceptions],Old=[types]} declared within
an unnamed @nt{block_statement}.]}
@begin{Ramification}
  Note that we're talking about the name of the exception,
  not the name of the occurrence.
@end{Ramification}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00400-01]}
@ChgAdded{Version=[2],Text=[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.]}
@ChgImplDef{Version=[2],Kind=[AddedNormal],Text=[@Chg{Version=[2],New=[
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).],Old=[]}]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00378-01],ARef=[AI95-00417-01]}
@ChgAdded{Version=[2],Text=[The string returned by the Exception_Name,
Wide_Exception_Name, and Wide_Wide_Exception_Name functions has lower bound 1.]}

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00378-01]}
Exception_Information returns implementation-defined information
about the exception occurrence.
@Chg{Version=[2],New=[The returned string has lower bound 1.],Old=[]}
@ImplDef{The information returned by Exception_Information.}

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00241-01],ARef=[AI95-00446-01]}
@Chg{Version=[2],New=[],Old=[Raise_Exception and ]}Reraise_Occurrence
@Chg{Version=[2],New=[has],Old=[have]} no effect in the case of
@Chg{Version=[2],New=[],Old=[Null_Id or ]}Null_Occurrence.
@Defn2{Term=[Constraint_Error],Sec=(raised by failure of run-time check)}
@Chg{Version=[2],New=[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.],
Old=[Exception_Message, Exception_Identity, Exception_Name, and
Exception_Information
raise Constraint_Error for a Null_Id or Null_Occurrence.]}

@begin{Ramification}
@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00241-01]}
@ChgAdded{Version=[2],Text=[Null_Occurrence can be tested for by comparing
Exception_Identity(Occurrence) to Null_Id.]}
@end{Ramification}

@begin{Discussion}
@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00446-01]}
@ChgAdded{Version=[2],Text=[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.]}
@end{Discussion}

The Save_Occurrence procedure copies the Source to the Target.
The Save_Occurrence function uses an @nt{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;
@Redundant[the result may be deallocated using an instance of
Unchecked_Deallocation.]
@begin{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.
@end{Ramification}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00438-01]}
@ChgAdded{Version=[2],Text=[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).]}
@ChgNote{All of these notes (except the first) are moved from below.}
@begin{Ramification}
  @ChgRef{Version=[2],Kind=[AddedNormal]}
  @ChgAdded{Version=[2],Text=[This routines are used to define the stream
  attributes (see @RefSecNum{Stream-Oriented Attributes}) for
  Exception_Occurrence.]}

  @ChgRef{Version=[2],Kind=[AddedNormal]}
  @ChgAdded{Version=[2],Text=[The identity of the exception,
  as well as the Exception_Name and Exception_Message,
  have to be preserved across partitions.]}

  @ChgRef{Version=[2],Kind=[AddedNormal]}
  @ChgAdded{Version=[2],Text=[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.]}
@end{Ramification}
@begin{Reason}
  @ChgRef{Version=[2],Kind=[AddedNormal]}
  @ChgAdded{Version=[2],Text=[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 @RefSecNum{Remote Subprogram Calls}).]}
@end{Reason}
@end{StaticSem}

@begin{ImplReq}
@ChgRef{Version=[2],Kind=[Deleted],ARef=[AI95-00438-01]}
@ChgDeleted{Version=[2],Text=[The implementation of the Write attribute
(see @RefSecNum{Stream-Oriented Attributes})
of Exception_Occurrence shall support writing
a representation of an exception occurrence
to a stream; the implementation of the Read attribute
of Exception_Occurrence shall support reconstructing
an exception occurrence from a stream (including one written in
a different partition).]}
@begin{Ramification}
  @ChgRef{Version=[2],Kind=[Deleted]}
  @ChgDeleted{Version=[2],Text=[The identity of the exception,
  as well as the Exception_Name and Exception_Message,
  have to be preserved across partitions.]}

  @ChgRef{Version=[2],Kind=[Deleted]}
  @ChgDeleted{Version=[2],Text=[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.]}
@end{Ramification}
@begin{Reason}
  @ChgRef{Version=[2],Kind=[Deleted]}
  @ChgDeleted{Version=[2],Text=[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 @RefSecNum{Remote Subprogram Calls}).]}
@end{Reason}
@end{ImplReq}

@begin{ImplPerm}
An implementation of Exception_Name in a space-constrained
environment may return the
@nt{defining_@!identifier} instead of the full expanded name.


The string returned by Exception_Message may be truncated (to no less
than 200 characters) by the Save_Occurrence procedure
@Redundant[(not the function)],
the Reraise_Occurrence procedure,
and the re-raise statement.
@begin{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
@lquotes@;one-liner@rquotes@;.
Note that an implementation is allowed to do this truncation even if it
supports arbitrarily long lines.
@end{Reason}
@end{ImplPerm}

@begin{ImplAdvice}
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.
@ChgImplAdvice{Version=[2],Kind=[Added],Text=[@ChgAdded{Version=[2],
Text=[Exception_Information should provide
information useful for debugging, and should include the Exception_Name
and Exception_Message.]}]}
@ChgImplAdvice{Version=[2],Kind=[Added],Text=[@ChgAdded{Version=[2],
Text=[Exception_Message by default should be short, provide
information useful for debugging, and should not include the Exception_Name.]}]}

@begin{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.
@end{Reason}
@begin{ImplNote}
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.

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.

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.

Note that exceptions behave as if declared at library level;
there is no @lquotes@;natural scope@rquotes@; 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.

@Leading@;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:
@begin{Example}
@key[type] Exception_Occurrence(Message_Length : Natural := 200) @key[is]
    @key[limited] @key[record]
        Id : Exception_Id;
        Message : String(1..Message_Length);
    @key[end] @key[record];
@end{Example}

@Leading@;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 @em none for an empty message. This is just like
declaring a constrained object of the type:
@begin{Example}
Temp : Exception_Occurrence(10); --@RI{ for a 10-character message}
@end{Example}

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.

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 @em as
the implementation sees fit.

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.

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

@Leading@;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 @em 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:
@begin{Example}
@key[type] Exception_Occurrence_Kind @key[is] (Normal, As_Choice_Param);

@key[type] Exception_Occurrence(Kind : Exception_Occurrence_Kind := Normal) @key[is]
    @key[limited] @key[record]
        @key[case] Kind @key[is]
            @key[when] Normal =>
                ... --@RI{ space for 200 characters}
            @key[when] As_Choice_Param =>
                ... --@RI{ pointer to heap string}
        @key[end] @key[case];
    @key[end] @key[record];
@end{Example}

Exception_Occurrences created by the run-time system during exception
raising would be As_Choice_Param. User-declared ones would be Normal @em 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.

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

@Leading@;One possible implementation of Reraise_Occurrence is as follows:
@begin{Example}
@key[procedure] Reraise_Occurrence(X : @key[in] Exception_Occurrence) @key[is]
@key[begin]
    Raise_Exception(Identity(X), Exception_Message(X));
@key[end] Reraise_Occurrence;
@end{Example}

However, some implementations may wish to retain more information
across a re-raise @em a stack traceback, for example.
@end{ImplNote}
@begin{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.
@end{Ramification}
@begin{ImplNote}
@ChgRef{Version=[2],Kind=[Deleted],ARef=[AI95-00400-01]}
@ChgDeleted{Version=[2],Text=[If an implementation chooses to have a mode in
which it supports non-Latin-1 characters in identifiers, then it needs to
define what the above functions return in the case where the name of an
exception contains such a character.]}
@end{ImplNote}
@end{ImplAdvice}

@begin{Extend83}
@Defn{extensions to Ada 83}
  The Identity attribute of exceptions is new, as is the package
  Exceptions.
@end{Extend83}

@begin{Inconsistent95}
  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00241-01]}
  @ChgAdded{Version=[2],Text=[@Defn{inconsistencies with Ada 95}
  @B[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.]}

  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00378-01],ARef=[AI95-00417-01]}
  @ChgAdded{Version=[2],Text=<@B[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.>}

  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00446-01]}
  @ChgAdded{Version=[2],Text=[@B[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.]}
@end{Inconsistent95}

@begin{Incompatible95}
  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00400-01],ARef=[AI95-00438-01]}
  @ChgAdded{Version=[2],Text=[@Defn{incompatibilities with Ada 95}
  Functions Wide_Exception_Name and Wide_Wide_Exception_Name, and procedures
  Read_Exception_Occurrence and Write_Exception_Occurrence
  are newly added to Exceptions. If Exceptions is referenced in a
  @nt{use_clause}, and an entity @i<E> with the same @nt{defining_identifier}
  as a new entity in Exceptions is defined in a
  package that is also referenced in a @nt{use_clause}, the entity @i<E> may no
  longer be use-visible, resulting in errors. This should be rare and is easily
  fixed if it does occur.]}
@end{Incompatible95}

@begin{Extend95}
  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00362-01]}
  @ChgAdded{Version=[2],Text=[@Defn{extensions to Ada 95}
  The package Exceptions is preelaborated, and types Exception_Id and
  Exception_Occurrence have preelaborable initialization, allowing this package
  to be used in preelaborated units.]}
@end{Extend95}

@begin{DiffWord95}
  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00361-01]}
  @ChgAdded{Version=[2],Text=[The meaning of Exception_Message is reworded to
  reflect that the string can come from a @nt{raise_statement} as well as a
  call of Raise_Exception.]}

  @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00400-01]}
  @ChgAdded{Version=[2],Text=[Added Wide_Exception_Name and
  Wide_Wide_Exception_Name
  because identifiers can now contain characters outside of Latin-1.]}
@end{DiffWord95}


@LabeledAddedSubClause{Version=[2],Name=[Pragmas Assert and Assertion_Policy]}

@begin{Intro}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[Pragma Assert is used to assert the truth of a
Boolean expression at any point within a sequence of declarations or statements.
Pragma Assertion_Policy is used to control whether such assertions@Defn{Assertions}
are to be ignored by the implementation, checked at run-time, or handled in
some implementation-defined manner.]}
@end{Intro}

@begin{Syntax}
@begin{SyntaxText}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[The form of a
@nt{pragma} Assert is as follows:]}
@end{SyntaxText}

@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=`@AddedPragmaSyn`Version=[2],@key{pragma} @prag<Assert>([Check =>] @SynI{boolean_}@Syn2{expression}[, [Message =>] @SynI{string_}@Syn2{expression}]);''}

@begin{SyntaxText}
@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[A @nt{pragma} Assert is allowed at the place where a
@nt{declarative_item} or a @nt{statement} is allowed.]}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[The form of a
@nt{pragma} Assertion_Policy is as follows:]}
@end{SyntaxText}

@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=<@AddedPragmaSyn`Version=[2],@key{pragma} @prag<Assertion_Policy>(@SynI{policy_}@Syn2{identifier});'>}

@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[@PDefn2{Term=[configuration pragma], Sec=(Assertion_Policy)}
@PDefn2{Term=[pragma, configuration], Sec=(Assertion_Policy)}
A @nt{pragma} Assertion_Policy is a configuration pragma.]}

@end{Syntax}

@begin{Resolution}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[The expected type for the
@Syni{boolean_}@nt{expression} of a @nt{pragma} Assert
is any boolean type. The expected type for the @Syni{string_}@nt{expression}
of a @nt{pragma} Assert is type String.]}
@begin{Reason}
  @ChgRef{Version=[2],Kind=[AddedNormal]}
  @ChgAdded{Version=[2],Text=[We allow any boolean type to be like
  @nt{if_statement}s and other conditionals; we only allow String for the
  message in order to match @nt{raise_statement}s.]}
@end{Reason}
@end{Resolution}


@begin{Legality}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[The @SynI<policy_>@nt<identifier> of a @nt{pragma}
Assertion_Policy shall be either Check, Ignore, or an implementation-defined
identifier.]}
@ChgImplDef{Version=[2],Kind=[AddedNormal],Text=[@Chg{Version=[2],New=[Implementation-defined
@SynI<policy_>@nt<identifier>s allowed in a @nt{pragma} Assertion_Policy.],Old=[]}]}
@end{Legality}

@begin{StaticSem}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[A @nt<pragma> Assertion_Policy is a configuration pragma
that specifies the assertion policy in effect for the compilation units to which it
applies. Different policies may apply to different compilation
units within the same partition. The default assertion policy is
implementation-defined.]}
@ChgImplDef{Version=[2],Kind=[AddedNormal],Text=[@Chg{Version=[2],New=[The
default assertion policy.],Old=[]}]}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[The following
language-defined library package exists:]}

@begin{Example}
@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[@ChildUnit{Parent=[Ada],Child=[Assertions]}@key[package] Ada.Assertions @key[is]
   @key[pragma] Pure(Assertions);]}

@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[   Assertion_Error : @key<exception>;]}

@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[   @key<procedure> Assert(Check : @key<in> Boolean);
   @key<procedure> Assert(Check : @key<in> Boolean; Message : @key<in> String);]}

@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[@key<end> Ada.Assertions;]}
@end{Example}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[A compilation unit containing a @nt{pragma} Assert has a
semantic dependence on the Assertions library unit.]}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[The assertion policy that applies to a generic unit
also applies to all its instances.]}
@end{StaticSem}


@begin{RunTime}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[An assertion policy @defn{assertion policy}specifies
how a @nt{pragma} Assert is interpreted by the implementation. If the assertion
policy is Ignore at the point of a @nt{pragma} Assert, the pragma is ignored.
If the assertion policy is Check at the point of a @nt{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.]}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[Calling the procedure
Assertions.Assert without a Message parameter is equivalent to:]}

@begin{Example}
@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[@key<if> Check = False @key<then>
   @key<raise> Ada.Assertions.Assertion_Error;
@key{end} @key{if};]}
@end{Example}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Type=[Leading],Keepnext=[T],Text=[Calling the procedure
Assertions.Assert with a Message parameter is equivalent to:]}

@begin{Example}
@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[@key<if> Check = False @key<then>
   @key<raise> Ada.Assertions.Assertion_Error @key<with> Message;
@key{end} @key{if};]}
@end{Example}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[The procedures Assertions.Assert have these
effects independently of the assertion policy in effect.]}

@end{RunTime}

@begin{ImplPerm}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[Assertion_Error may be declared by renaming an
implementation-defined exception from another package.]}
@begin{Reason}
@ChgRef{Version=[2],Kind=[AddedNormal]}
@ChgAdded{Version=[2],Text=[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.]}
@end{Reason}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[Implementations may define their own assertion policies.]}
@end{ImplPerm}

@begin{Notes}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[Normally, the boolean expression in a @nt{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.]}
@end{Notes}

@begin{Extend95}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00286-01]}
@ChgAdded{Version=[2],Text=[@Defn{extensions to Ada 95}
Pragmas Assert and Assertion_Policy, and package Assertions are new.]}
@end{Extend95}

@LabeledSubClause{Example of Exception Handling}

@begin{Examples}
@Leading@;Exception handling may be used to separate the detection of an error
from the response to that error:
@begin{Example}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00433-01]}
@Chg{Version=[2],New=[],Old=[@key[with] Ada.Exceptions;
@key[use] Ada;
]}@key[package] File_System @key[is]
    @key[type] File_Handle @key[is] @key[limited] @key[private];

    File_Not_Found : @key[exception];
    @key[procedure] Open(F : @key[in] @key[out] File_Handle; Name : String);
        --@RI{ raises File_Not_Found if named file does not exist}

    End_Of_File : @key[exception];
    @key[procedure] Read(F : @key[in] @key[out] File_Handle; Data : @key[out] Data_Type);
        --@RI{ raises End_Of_File if the file is not open}

    ...
@key[end] File_System;


@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00433-01]}
@key[package] @key[body] File_System @key[is]
    @key[procedure] Open(F : @key[in] @key[out] File_Handle; Name : String) @key[is]
    @key[begin]
        @key[if] File_Exists(Name) @key[then]
            ...
        @key[else]
            @Chg{Version=[2],New=[@key[raise] ],Old=[Exceptions.Raise_Exception(]}File_Not_Found@Chg{Version=[2],New=[ @key[with] ],Old=['Identity,
                                      ]}"File not found: " & Name & "."@Chg{Version=[2],New=[],Old=[)]};
        @key[end] @key[if];
    @key[end] Open;

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

    ...

@key[end] File_System;


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


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.
@end{Examples}

@begin{DiffWord83}
The sections labeled @lquotes@;Exceptions Raised During ...@rquotes@;
are subsumed by this clause,
and by parts of Section 9.
@end{DiffWord83}

@LabeledClause{Suppressing Checks}

@begin{Intro}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
@Chg{Version=[2],New=[@i{Checking pragmas}@Defn{Checking pragmas} give
instructions to an implementation on handling language-defined checks.],Old=[]}
A @nt{pragma} Suppress gives permission to an
implementation to omit certain language-defined checks@Chg{Version=[2],
New=[, while a @nt<pragma> Unsuppress revokes the permission to omit checks.],Old=[]}.

@Defn{language-defined check}
@Defn2{Term=[check], Sec=(language-defined)}
@IndexSee{Term=[run-time check],See=(language-defined check)}
@Defn{run-time error}
@Defn2{Term=[error], Sec=(run-time)}
A @i{language-defined check} (or simply, a @lquotes@;check@rquotes@;) 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.
@Defn2{Term=[failure],Sec=(of a language-defined check)}
A check @i{fails} when the condition being checked is false,
causing an exception to be raised.
@begin{Discussion}
All such checks are defined under @lquotes@;@RunTimeTitle@rquotes@;
in clauses and subclauses throughout the standard.
@end{Discussion}
@end{Intro}

@begin{Syntax}
@begin{SyntaxText}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
@Leading@Keepnext@;The form@Chg{Version=[2],New=[s of checking pragmas are],Old=[ of a @nt{pragma} Suppress is]} as follows:
@end{SyntaxText}

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
@PragmaSyn`@key{pragma} @prag(Suppress)(@Syn2{identifier}@Chg{Version=[2],New=<>,Old=( [, [On =>] @Syn2{name}])});'

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=<@AddedPragmaSyn`Version=[2],@key{pragma} @prag(Unsuppress)(@Syn2{identifier});'>}

@begin{SyntaxText}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
@PDefn2{Term=[configuration pragma], Sec=(Suppress)}
@PDefn2{Term=[pragma, configuration], Sec=(Suppress)}
@Chg{Version=[2],New=[@PDefn2{Term=[configuration pragma], Sec=(Unsuppress)}
@PDefn2{Term=[pragma, configuration], Sec=(Unsuppress)}],Old=[]}
A @Chg{Version=[2],New=<checking pragma>,Old=<@nt{pragma} Suppress>} is
allowed only immediately within a
@nt{declarative_part}, immediately within a @nt{package_@!specification},
or as a configuration pragma.
@end{SyntaxText}
@end{Syntax}

@begin{Legality}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
The @nt{identifier} shall be the name of a check.
@Chg{Version=[2],New=<>,Old=<The @nt{name} (if present) shall statically denote
some entity.>}

@ChgRef{Version=[2],Kind=[Deleted],ARef=[AI95-00224-01]}
@ChgDeleted{Version=[2],Text=<For a @nt{pragma} Suppress that is immediately
within a @nt{package_specification} and includes a @nt<name>, the @nt<name>
shall denote an entity (or several overloaded subprograms) declared immediately
within the @nt{package_specification}.>}
@end{Legality}

@begin{StaticSem}
@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[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
@nt<declarative_part> or immediately within a @nt<package_specification>
applies from the place of the @nt<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.]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[If a checking pragma applies to a generic instantiation, then the checking
pragma also applies to the instance. If a checking pragma applies to a call to
a subprogram that has a @nt<pragma> Inline applied to it, then the checking
pragma also applies to the inlined subprogram body.]}

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
A @nt{pragma} Suppress gives permission to an implementation to omit the
named check @Chg{Version=[2],New=[(or every check in the case of All_Checks) for any entities to which it
applies.],Old=[from the place of the @nt{pragma} to the end of the
innermost enclosing declarative region, or,
if the @nt{pragma} is given in a @nt{package_@!specification}
and includes a @nt<name>,
to the end of the scope of the named entity.
If the @nt{pragma} includes a @nt{name},
the permission applies only to checks performed on the named entity,
or, for a subtype, on objects and values of its type.
Otherwise, the permission applies to all entities.]}
@Defn{suppressed check}
If permission has been given to suppress a given check,
the check is said to be @i{suppressed}.
@begin{Ramification}
A check is suppressed even if the implementation chooses not to
actually generate better code.
@Defn2{Term=[Program_Error],Sec=(raised by failure of run-time check)}
This allows the implementation to raise Program_Error,
for example, if the erroneousness is detected.
@end{Ramification}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[A @nt{pragma} Unsuppress revokes the permission
to omit the named check (or every check in the case of All_Checks) given by any
@nt{pragma} Suppress that applies at the point of the @nt{pragma} Unsuppress.
The permission is revoked for the region to which the @nt{pragma} Unsuppress
applies. If there is no such permission at the point of a @nt{pragma}
Unsuppress, then the @nt{pragma} has no effect. A later @nt{pragma} Suppress
can renew the permission.]}

@Leading@Keepnext@;The following are the language-defined checks:
@begin{Itemize}
@Defn2{Term=[Constraint_Error],Sec=(raised by failure of run-time check)}
@Leading@Redundant[The following checks correspond to situations in which the
exception Constraint_Error is raised upon failure.]
@begin{Description}
@ChgRef{Version=[1],Kind=[Revised],Ref=[8652/0036],ARef=[AI95-00176-01]}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00231-01]}
@RootDefn{Access_Check}
Access_Check @\@Redundant[When evaluating a dereference (explicit
or implicit),
check that the value of the @nt{name} is not @key{null}.
@Chg{Version=[2],New=[When converting to a subtype that excludes null,
check that the converted value is not @key{null}.],
Old=[When passing an actual parameter to a formal access parameter,
check that the value of the actual parameter is not @key{null}.
@Chg{Version=[1],New=[When evaluating a @nt{discriminant_association} for an
access discriminant, check that the value of the discriminant is not @key{null}.],
Old=[]}]}]

@RootDefn{Discriminant_Check}
Discriminant_Check @\@Redundant[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.]

@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00434-01]}
@RootDefn{Division_Check}
Division_Check @\@Redundant[Check that the second operand is not zero
for the
operations /, @Chg{Version=[2],New=[@key[rem]],Old=[rem]} and
@Chg{Version=[2],New=[@key[mod]],Old=[mod]}.]

@RootDefn{Index_Check}
Index_Check @\@Redundant[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.]

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

@RootDefn{Overflow_Check}
Overflow_Check @\@Redundant[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.]

@RootDefn{Range_Check}
Range_Check @\@Redundant[Check that a scalar value satisfies a range
constraint.
Also, for the elaboration of a @nt<subtype_indication>, check that
the @nt<constraint> (if present) is compatible with the
subtype denoted by the @nt{subtype_mark}.
Also, for an @nt<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.]

@RootDefn{Tag_Check}
Tag_Check @\@Redundant[Check that operand tags in a dispatching call
are all equal.
Check for the correct tag on tagged type conversions,
for an @nt{assignment_statement},
and when returning a tagged limited object from a function.]
@end{Description}

@Defn2{Term=[Program_Error],Sec=(raised by failure of run-time check)}
@Leading@Redundant[The following checks correspond to situations in which the
exception Program_Error is raised upon failure.]
@begin{Description}
@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00280]}
@ChgAdded{Version=[2],Text=[@RootDefn{Accessibility_Check}
Accessibility_Check @\@Redundant[Check the accessibility level of an
entity or view.]]}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00280]}
@ChgAdded{Version=[2],Text=[@RootDefn{Allocation_Check}
Allocation_Check @\@Redundant[For an @nt<allocator>, check that the master of
any tasks to be created by the @nt{allocator} is not yet completed or some
dependents have not yet terminated, and that the finalization of the
collection has not started.]]}

@RootDefn{Elaboration_Check}
Elaboration_Check @\@Redundant[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.]

@ChgRef{Version=[2],Kind=[Deleted],ARef=[AI95-00280]}
@ChgNote{This item is not in alphabetical order}
@ChgDeleted{Version=[2],Text=[@RootDefn{Accessibility_Check}
Accessibility_Check @\@Redundant[Check the accessibility level of an
entity or view.]]}

@end{Description}

@Leading@Redundant[The following check corresponds to situations in which the
exception Storage_Error is raised upon failure.]
@begin{Description}
@RootDefn{Storage_Check}
@Defn2{Term=[Storage_Error],Sec=(raised by failure of run-time check)}
Storage_Check @\@Redundant[Check that evaluation of an @nt{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.]
@begin{Reason}
We considered splitting this out into three categories:
Pool_Check (for @nt{allocator}s), Stack_Check (for stack usage),
and Heap_Check (for implicit use of the heap @em use of the heap
other than through an @nt{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.
@end{Reason}
@end{Description}

@Leading@Redundant[The following check corresponds to all situations in which
any predefined exception is raised.]
@begin{Description}
@RootDefn{All_Checks}
All_Checks @\Represents the union of all checks;
@Redundant[suppressing All_Checks suppresses all checks.]
@begin{Ramification}
All_Checks includes both language-defined and implementation-defined
checks.
@end{Ramification}
@end{Description}
@end{Itemize}
@end{StaticSem}

@begin{Erron}
@PDefn2{Term=(erroneous execution),Sec=(cause)}
If a given check has been suppressed,
and the corresponding error situation occurs,
the execution of the program is erroneous.
@end{Erron}

@begin{ImplPerm}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
An implementation is allowed to place restrictions on
@Chg{Version=[2],New=[checking pragmas, subject only to the requirement that
@nt{pragma} Unsuppress shall allow any
check names supported by @nt{pragma} Suppress],Old=[Suppress @nt<pragma>s]}.
An implementation is allowed to add additional check names,
with implementation-defined semantics.
@PDefn{unspecified}
When Overflow_Check has been suppressed,
an implementation may also suppress an unspecified
subset of the Range_Checks.
@begin{Reason}
@ChgRef{Version=[2],Kind=[Deleted],ARef=[AI95-00224-01]}
@ChgDeleted{Version=[2],Text=[The permission to restrict is given
so the implementation can give an error message when the
requested suppression is nonsense, such as suppressing a Range_Check
on a task type.
It would be verbose and pointless to list all the cases of
nonsensical language-defined checks in the standard,
and since the list of checks is open-ended,
we can't list the restrictions for implementation-defined checks
anyway.]}
@end{Reason}
@ImplDef{Implementation-defined check names.}
@begin{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).
@end{Discussion}

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[An implementation may support an additional
parameter on
@nt{pragma} Unsuppress similar to the one allowed for @nt{pragma} Suppress
(see @RefSecNum{Specific Suppression of Checks}). The meaning of
such a parameter is implementation-defined.]}
@ChgImplDef{Version=[2],Kind=[Added],Text=[@Chg{Version=[2],New=[Existence and
meaning of second parameter of @nt{pragma} Unsuppress.],Old=[]}]}
@end{ImplPerm}

@begin{ImplAdvice}
The implementation should minimize the code executed for checks
that have been suppressed.
@ChgImplAdvice{Version=[2],Kind=[Added],Text=[@ChgAdded{Version=[2],
Text=[Code executed for checks
that have been suppressed should be minimized.]}]}
@begin{ImplNote}
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.
@end{ImplNote}
@end{ImplAdvice}

@begin{Notes}
@Defn{optimization}
@Defn{efficiency}
There is no guarantee that a suppressed check is actually removed;
hence a @nt{pragma} Suppress should be used only for efficiency reasons.

@ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[It is possible to give both a @nt{pragma} Suppress
and Unsuppress for the same check immediately within the same
@nt{declarative_part}.
In that case, the last @nt{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 @nt{pragma} Suppress in an inner declarative region.]}
@end{Notes}

@begin{Examples}
@Leading@Keepnext@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
@i{Examples of suppressing @Chg{Version=[2],New=[and unsuppressing ],Old=[]}checks:}
@begin{Example}
@ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00224-01]}
@key[pragma] Suppress(@Chg{Version=[2],New=[Index_Check);
@key[pragma] Unsuppress(Overflow_Check);],Old=[Range_Check);
@key[pragma] Suppress(Index_Check, On => Table);]}
@end{Example}
@end{Examples}

@begin{Extend83}
@Defn{extensions to Ada 83}
A @nt{pragma} Suppress is allowed as a configuration pragma.
A @nt{pragma} Suppress without a @nt<name> is allowed in a
@nt{package_specification}.

Additional check names are added.
We allow implementations to define their own checks.
@end{Extend83}

@begin{DiffWord83}
We define the checks in a distributed manner.
Therefore, the long list of what checks apply to what
is merely a NOTE.

We have removed the detailed rules about what is allowed
in a @nt{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.

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 @em
the non-uniformity in this case is not harmful,
and removing it would have a serious impact on optimizers.

Under Access_Check,
dereferences cover the cases of
@nt{selected_component}, @nt{indexed_component}, @nt{slice},
and attribute that are listed in RM83,
as well as the new @nt{explicit_dereference},
which was included in @nt{selected_component} in RM83.
@end{DiffWord83}

@begin{Extend95}
@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[@Defn{extensions to Ada 95}Pragma Unsuppress is new.]}

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00280-01]}
@ChgAdded{Version=[2],Text=[Allocation_Check was added to support suppressing
the new check on @nt{allocator}s (see @RefSecNum{Allocators}).]}
@end{Extend95}

@begin{DiffWord95}
@ChgRef{Version=[2],Kind=[AddedNormal],Ref=[8652/0036],ARef=[AI95-00176-01],ARef=[AI95-00224-01]}
@ChgAdded{Version=[2],Text=[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.]}

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

@ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00280-01]}
@ChgAdded{Version=[2],Text=[The order of the
Program_Error checks was corrected to be alphabetical.]}
@end{DiffWord95}

@LabeledClause{Exceptions and Optimization}

@begin{Intro}
@redundant[@Defn{language-defined check}
@Defn2{Term=[check], Sec=(language-defined)}
@Defn{run-time error}
@Defn2{Term=[error], Sec=(run-time)}
@Defn{optimization}
@Defn{efficiency}
This clause gives permission to the implementation to perform
certain @lquotes@;optimizations@rquotes@; that do not necessarily preserve the canonical
semantics.]
@end{Intro}

@begin{RunTime}
@Defn{canonical semantics}
The rest of this International Standard (outside this clause)
defines the @i{canonical semantics} of the language.
@Redundant[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.]
@begin{Ramification}
Note that the canonical semantics is a set of possible behaviors,
since some reordering, parallelism, and non-determinism is allowed by
the canonical semantics.
@end{Ramification}
@begin{Discussion}
@Leading@;The following parts of the canonical semantics are of particular
interest to the reader of this clause:
@begin{Itemize}
Behavior in the presence of abnormal objects
and objects with invalid representations
(see @RefSecNum{Data Validity}).

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

Behavior in the presence of a misuse of Unchecked_Deallocation,
Unchecked_Access, or imported or exported entity
(see Section 13).
@end{Itemize}
@end{Discussion}

@Redundant[As explained in
@RefSec{Conformity of an Implementation with the Standard},
the external effect of a program is defined in terms of its
interactions with its external environment.
Hence, the implementation can perform any internal
actions whatsoever, in any order or in parallel,
so long as the external effect of the execution of the program is one
that is allowed by the canonical semantics, or by the rules
of this clause.]
@begin{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.
@end{Ramification}
@end{RunTime}

@begin{ImplPerm}
@Leading@;The following additional permissions are granted to the
implementation:
@begin{Itemize}
@Defn{extra permission to avoid raising exceptions}
@Defn{undefined result}
An implementation need not always
raise an exception when a language-defined check fails.
Instead, the operation that failed the check can simply yield
an @i{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.
@Redundant[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.]
@begin{Ramification}
Even without this permission, an implementation can always
remove a check if it cannot possibly fail.
@end{Ramification}
@begin{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.
@end{Reason}
@begin{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.
@end{Discussion}
@begin{ImplNote}
  @Leading@;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:
@begin{Example}
  @key[if] X * Y > Integer'Last @key[then]
      Put_Line("X * Y overflowed");
  @key[end] @key[if];
@key[exception]
  @key[when] @key[others] =>
      Put_Line("X * Y overflowed");
@end{Example}
  @ChgNote{The following paragraph is missing a number in the original version.
  To give it a number in the new version, it is marked as an insertion.}
  @ChgRef{Version=[0],Kind=[Added]}
  @Chg{New=[],Old=[@Noparanum@;]}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.

  @Leading@;As another example where a raise may not be eliminated:
@begin{Example}
  @key[subtype] Str10 @key[is] String(1..10);
  @key[type] P10 @key[is] @key[access] Str10;
  X : P10 := @key[null];
@key[begin]
  @key[if] X.all'Last = 10 @key[then]
      Put_Line("Oops");
  @key[end] @key[if];
@end{Example}
  @ChgNote{The following paragraph is missing a number in the original version.
  To give it a number in the new version, it is marked as an insertion.}
  @ChgRef{Version=[0],Kind=[Added]}
  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."
@end{ImplNote}

@Defn{extra permission to reorder actions}
If an exception is raised due to the failure
of a language-defined check,
then upon
reaching the corresponding @nt<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 @nt<sequence_of_statements> with the handler
(or the @nt<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 @i(independent) subprogram
that does not dynamically enclose the execution of the construct
whose check failed.
@Defn{independent subprogram}
An independent subprogram is one that is
defined outside the library unit containing the construct whose check
failed, and has no Inline @nt<pragma> applied to it.
@Defn{normal state of an object}
@PDefn{abnormal state of an object}
@PDefn{disruption of an assignment}
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 @RefSecNum{Data Validity}.
@begin{Reason}
  We allow such variables to become abnormal so that
  assignments (other than to atomic variables) can be disrupted
  due to @lquotes@;imprecise@rquotes@; 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.
@end{Reason}
@begin{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.
@end{Ramification}
@end{Itemize}
@begin{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?

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

Consider the two extremes:

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

The extreme liberal rule would be @lquotes@;the language does not specify the
execution of a program once a language-defined check has failed;
such execution can be unpredictable.@rquotes@;
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.

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

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.
@end{Discussion}
@end{ImplPerm}

@begin{Notes}
The permissions granted by this clause can have an effect on the
semantics of a program only if the program fails a language-defined check.
@end{Notes}

@begin{DiffWord83}
@Leading@;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:
@begin{Itemize}
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 @lquotes@;extra@rquotes@;
permission beyond what the rest of the document allows.

Paragraphs 3 and 4 are reflected in the
@lquotes@;extra permission to reorder actions@rquotes@;.
Note that this permission now allows the reordering of assignments in
many cases.

Paragraph 5 is moved to @RefSec{Operators and Expression Evaluation},
where operator association is discussed.
Hence, this is no longer an @lquotes@;extra permission@rquotes@;
but is part of the canonical semantics.

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.

Paragraph 7 is reflected in the
@lquotes@;extra permission to avoid raising exceptions@rquotes@;.
@end{Itemize}

We moved clause @RefSec{Suppressing Checks} from after 11.6 to
before 11.6, in order to preserve the famous number @lquotes@;11.6@rquotes@;
(given the changes to earlier clauses in Section 11).
@end{DiffWord83}
