theMayer
theMayer

Reputation: 16167

How To Raise Exception with Message in Ada

I'm struggling a little bit to raise exceptions the way I'm used to coming from a C# background.

I have a utility function that expects input values to be in a very specific range, as defined by an external standard. If a value is supplied outside of that range (and there is one value in the middle of the range that is also invalid), then I want to raise an exception to the caller so that they break.

From what I can tell, the syntax is raise Invalid_Argument;

But- is it possible to supply a message with the exception? e.g. the Invalid_Argument exception is somewhat self-explanatory, but I could see further detail specifying what was wrong with the argument. How do I write a brief error message to be stuck into the exception?

Upvotes: 2

Views: 1719

Answers (2)

Jeffrey R. Carter
Jeffrey R. Carter

Reputation: 3358

First, you can define a [sub]type

[sub]type Valid_Range_For_X is [Integer] range 23 .. 2001;

This will catch most invalid values automatically. If you're using Ada 12, you can add

[sub]type Valid_Range_For_X is [Integer] range 23 .. 2001 with
   Dynamic_Predicate => Valid_Range_For_X /= 42;

which will catch the internal invalid value as well. It's usually better to let the language do such checks for you than to do them manually.

If you're using an earlier version of Ada, then you'll have to manually check for the internal value. I usually prefer fine-grained exceptions to a general exception used for many things, differentiated by the exception message. So I would raise something like

X_Is_42

rather than

Invalid_Argument with "X is 42"

This makes it easier to distinguish the 42 case from the (often many) other kinds of invalid arguments. I realize not everyone agrees with this.

Upvotes: 3

Simon Wright
Simon Wright

Reputation: 25501

It used (Ada 95) to be you had to write

Ada.Exceptions.Raise_Exception (Invalid_Argument’Identity,
                                "message");

(see Ada95RM 11.4.2(6)) but since Ada 2005 you’ve been able to say

raise Invalid_Argument with "message";

(A2005RM 11.3).

Note that the string part is a string expression, so you can add something to describe the actual invalid value if that would be useful.

Upvotes: 5

Related Questions