Is there a way to specify a custom error/on failure message for pre- and postconditions, by analogy with Predicate_Failure
for predicates? I can't seem to be able to find anything in the official documentation. TIA.
Asked
Active
Viewed 100 times
2

Arets Paeglis
- 3,856
- 4
- 35
- 44
1 Answers
5
You could use a raise expression (see e.g here) as shown in the example below.
main.adb
pragma Assertion_Policy (Check);
with Ada.Text_IO;
with Ada.Float_Text_IO;
procedure Main is
package TIO renames Ada.Text_IO;
package FIO renames Ada.Float_Text_IO;
function Reciprocal (X : Float) return Float is (1.0 / X)
with Pre => (X /= 0.0 or else
raise Constraint_Error with "X must not be 0.");
begin
FIO.Put (Reciprocal (2.0));
TIO.New_Line;
FIO.Put (Reciprocal (0.0));
TIO.New_Line;
end Main;
output
$ ./obj/main
5.00000E-01
raised CONSTRAINT_ERROR : X must not be 0.
[2020-07-03 22:20:25] process exited with status 1, elapsed time: 00.32s

DeeDee
- 5,654
- 7
- 14
-
That's perfect, thank you! Somehow missed the obvious here. – Arets Paeglis Jul 03 '20 at 20:31
-
1You're welcome. I updated the example slightly: you can also use `or else` instead of an `if` expression. – DeeDee Jul 03 '20 at 20:35