Skip to main content

11.4 Exception Handling


This Reference Manual output has not been verified, and may contain omissions or errors. Report any problems on the tracking issue


[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.]

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


Within a given task, if the execution of construct a is defined by this document 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.

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

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:

  • If the construct is a task_body, the exception does not propagate further;
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.
  • 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.
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.

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.

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.
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.
Term entry: handle an exception — perform some actions in response to the arising of an exception
NOTE 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


The following language-defined library package exists:

with Ada.Streams;
package Ada.Exceptions  
    with  Preelaborate, Nonblocking, Global => in out synchronized is 
    type Exception_Id is private 
        with  Preelaborable_Initialization ;
    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;
type Exception_Occurrence is limited private with Preelaborable_Initialization ; type Exception_Occurrence_Access is access all Exception_Occurrence; Null_Occurrence : constant Exception_Occurrence; 4/3
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
function Exception_Identity(X : Exception_Occurrence) return Exception_Id; function Exception_Name(X : Exception_Occurrence) return String; -- Same as Exception_Name(Exception_Identity(X)). function Wide_Exception_Name(X : Exception_Occurrence) return Wide_String; -- Same as Wide_Exception_Name(Exception_Identity(X)). function Wide_Wide_Exception_Name(X : Exception_Occurrence) return Wide_Wide_String; -- Same as Wide_Wide_Exception_Name(Exception_Identity(X)). function Exception_Information(X : Exception_Occurrence) return String; 6/2
procedure Save_Occurrence(Target : out Exception_Occurrence; Source : in Exception_Occurrence); function Save_Occurrence(Source : Exception_Occurrence) return Exception_Occurrence_Access; 6.1/2
procedure Read_Exception_Occurrence (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : out Exception_Occurrence); procedure Write_Exception_Occurrence (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : in Exception_Occurrence); 6.2/2
for Exception_Occurrence'Read use Read_Exception_Occurrence; for Exception_Occurrence'Write use Write_Exception_Occurrence; 6.3/2
private ... -- not specified by the language end Ada.Exceptions;

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.


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


E'Identity returns the unique identity of the exception. The type of this attribute is Exception_Id.
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.

Raise_Exception raises a new occurrence of the identified exception.


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.

implementation defined
The information returned by Exception_Message.
implementation advice
There is about the contents of this string for language-defined checks.
Given an exception E, the raise_statement:
raise E;
is equivalent to this call to Raise_Exception:
Raise_Exception(E'Identity, Message => implementation-defined-string);
Similarly, the raise_statement:
raise E with "some information";
is equivalent to this call to Raise_Exception:
Raise_Exception(E'Identity, Message => "some information");

Reraise_Occurrence reraises the specified exception occurrence.

The following handler:
when others =>
is equivalent to this one:
when X : others =>

Exception_Identity returns the identity of the exception of the occurrence.


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.

See the Implementation Permission below.
To be honest: This name, as well as each prefix of it, does not denote a renaming_declaration.
implementation defined
The result of Exceptions.Wide_Wide_Exception_Name for exceptions declared within an unnamed block_statement.
Note that we're talking about the name of the exception, not the name of the occurrence.

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.

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

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


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

implementation defined
The information returned by Exception_Information.

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.

Null_Occurrence can be tested for by comparing Exception_Identity(Occurrence) to Null_Id.
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.

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

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

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

These routines are used to define the stream attributes (see 13.13.2) for Exception_Occurrence.
The identity of the exception, as well as the Exception_Name and Exception_Message, have to be preserved across partitions.
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.
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


An implementation of Exception_Name in a space-constrained environment may return the 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 [(not the function)], the Reraise_Occurrence procedure, and the re-raise statement.

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


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.

implementation advice
Exception_Information should provide information useful for debugging, and should include the Exception_Name and Exception_Message.
implementation advice
Exception_Message by default should be short, provide information useful for debugging, and should not include the Exception_Name.
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.
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.
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 “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.
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:
type Exception_Occurrence(Message_Length : Natural := 200) is
limited record
Id : Exception_Id;
Message : String(1..Message_Length);
end record;
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:
Temp : Exception_Occurrence(10); -- for a 10-character message
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 — 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.
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:
type Exception_Occurrence_Kind is (Normal, As_Choice_Param);
19.ptype 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;
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.
This alternative implementation corresponds to a heap-based implementation of functions returning unknown-sized results.
One possible implementation of Reraise_Occurrence is as follows:
procedure Reraise_Occurrence(X : in Exception_Occurrence) is
Raise_Exception(Identity(X), Exception_Message(X));
end Reraise_Occurrence;
However, some implementations may wish to retain more information across a re-raise — a stack traceback, for example.
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.
This paragraph was deleted.
NOTE UTF-8 encoding (see A.4.11) can be used to represent non-ASCII characters in exception messages.

Extensions to Ada 83

The Identity attribute of exceptions is new, as is the package Exceptions.

Inconsistencies With Ada 95

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

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

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

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.
Added Wide_Exception_Name and Wide_Wide_Exception_Name because identifiers can now contain characters outside of Latin-1.

Wording Changes from Ada 2005

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


Pragma Assert is used to assert the truth of a boolean expression at a point within a sequence of declarations or statements.


Assert pragmas, subtype predicates (see 3.2.4), preconditions and postconditions (see 6.1.1), type invariants (see 7.3.2), and default initial conditions (see 7.3.3) are collectively referred to as assertions; their boolean expressions are referred to as assertion expressions.

Term entry: assertion — boolean expression that is expected to be True at run time at certain specified places


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.



The form of a pragma Assert is as follows:


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


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


The form of a pragma Assertion_Policy is as follows:


pragma Assertion_Policy(policy_identifier);


pragma Assertion_Policy(
assertion_aspect_mark => policy_identifier
{, assertion_aspect_mark => policy_identifier});


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


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.

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


The assertion_aspect_mark of a pragma Assertion_Policy shall identify an assertion aspect, namely one of Assert, Static_Predicate, Dynamic_Predicate, Pre, Pre'Class, Post, Post'Class, Type_Invariant, Type_Invariant'Class, Default_Initial_Condition, or some implementation-defined (assertion) aspect_mark. The policy_identifier shall be either Check, Ignore, or some implementation-defined identifier.

implementation defined
Implementation-defined policy_identifiers and assertion_aspect_marks allowed in a pragma Assertion_Policy.
To be honest: “Assert” is considered an “assertion aspect” for the purposes of this rule, even though there is no sort of entity that has an Assert aspect. It can only be specified using an Assert pragma, and applies to a particular point in the execution of a logical thread of control.

Static Semantics


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 runtime 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 runtime 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.]


If no assertion_aspect_marks are specified in the pragma, the specified policy applies to all assertion aspects.


A pragma Assertion_Policy applies to the named assertion aspects in a specific region, and applies to all assertion expressions associated with those aspects 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.


If a pragma Assertion_Policy applies to a generic_instantiation, then the pragma Assertion_Policy applies to the entire instance.

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.

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.

implementation defined
The default assertion policy.

The following language-defined library package exists:

package Ada.Assertions 
    with  Pure is 
13/2Assertion_Error : exception;
14/2procedure Assert(Check : in Boolean);
   procedure Assert(Check : in Boolean; Message : in String);
15/2end Ada.Assertions;

A compilation unit containing a check for an assertion (including a pragma Assert) has a semantic dependence on the Assertions library unit.


This paragraph was deleted.

Dynamic Semantics


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.


Calling the procedure Assertions.Assert without a Message parameter is equivalent to:

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

Calling the procedure Assertions.Assert with a Message parameter is equivalent to:

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

The procedures Assertions.Assert have these effects independently of the assertion policy in effect.

Bounded (Run-Time) Errors


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 can result in deadlock or a (nested) protected action.

Implementation Requirements


Any postcondition expression, type invariant expression, or default initial condition expression occurring in the specification of a language-defined unit is enabled (see 6.1.1, 7.3.2, and 7.3.3).

The Assertion_Policy does not have an effect on such postconditions, invariants, and default initial conditions. This has no execution impact since such assertions shouldn't fail anyway (see the next rule).

The evaluation of any such postcondition, type invariant, or default initial condition expression shall either yield True or propagate an exception from a raise_expression that appears within the assertion expression.

In other words, evaluating such an assertion expression will not return a result of False, nor will it propagate an exception other than by evaluating a raise_expression which is syntactically all or part of the assertion expression.
To be honest: Evaluation of any expression might raise Storage_Error.
This allows the Reference Manual to express semantic requirements as postconditions, invariants, or default initial conditions (which are invariably clearer than English prose would be) while keeping it clear that failing the assertion check (or any other run time check) is not conforming behavior.

Any precondition expression occurring in the specification of a language-defined unit is enabled (see 6.1.1) unless suppressed (see 11.5). Similarly, any predicate checks for a subtype occurring in the specification of a language-defined unit are enabled (see 3.2.4) unless suppressed.

This allows the Reference Manual to express runtime requirements on the client of a language-defined unit as preconditions or predicates (which are clearer than English prose would be). Some such requirements can be suppressed with pragma Suppress. Ada 2012 and earlier versions did not provide a mechanism to suppress such code.

Implementation Permissions


Assertion_Error may be declared by renaming an implementation-defined exception from another package.

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.

Implementations may define their own assertion policies.


If the result of a function call in an assertion is not used 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.]


An implementation may disallow the specification of an assertion expression if the evaluation of the expression has a side effect such that an immediate reevaluation of the expression can produce a different value. Similarly, an implementation may disallow 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 can produce a different value than in the case when the first expression had not been evaluated.

This allows an implementation to reject such assertions. To maximize portability, assertions should not include expressions that contain these sorts of side effects.
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.
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

Our intent is that any assertion expression that violates this Implementation Permission 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 meantime 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.
NOTE 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

Pragmas Assert and Assertion_Policy, and package Assertions are new.

Incompatibilities With Ada 2005

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

Assertion_Policy pragmas are now allowed in more places and can specify behavior for individual kinds of assertions.

Wording Changes from Ada 2012

Added wording that preconditions and predicates given on language-defined units are always checked unless suppressed (that is, they act like language-defined checks). This is not considered an inconsistency, since there are no such preconditions or predicates in Ada 2012.
Added wording that postconditions, type invariants, and default initial conditions given on language-defined units cannot fail. This is not considered an inconsistency, since there are no such postconditions, invariants, or default initial conditions in Ada 2012.
Added default initial conditions to the kinds of assertions (see 7.3.3).
Added a definition of assertion aspects, used in some freezing rules (see 13.14).

11.4.3 Example of Exception Handling



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

package File_System is
    type Data_Type is ...;
    type File_Handle is limited private;
3File_Not_Found : exception;
    procedure Open(F : in out File_Handle; Name : String);
        -- raises File_Not_Found if named file does not exist
4End_Of_File : exception;
    procedure Read(F : in out File_Handle; Data : out Data_Type);
        -- raises End_Of_File if the file is not open
... private ... end File_System;
The first ... provides a place for Close to be declared, and the second ... provides a place for File_Handle to be completed.
package body File_System is
This ... provides a place for File_Exists and the body of Close to be declared.

    procedure Open(F : in out File_Handle; Name : String) is
        if File_Exists(Name) then
            raise File_Not_Found with "File not found: " & Name & ".";
        end if;
    end Open;
7procedure Read(F : in out File_Handle; Data : out Data_Type) is
        if F.Current_Position <= F.Last_Position then
            raise End_Of_File;
        end if;
    end Read;
9end File_System;
with Ada.Text_IO; with Ada.Exceptions; with File_System; use File_System; use Ada; procedure Main is Verbosity_Desired : Boolean := ...; 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;

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 can have different handlers, even though the exceptional situations arise from the same basic causes.

Wording Changes from Ada 83

The sections labeled “Exceptions Raised During ...” are subsumed by this subclause, and by parts of Clause 9.