Coding Ada: Using an exception
Some people wonder where you can use a simple exception in Ada. Functions are an ideal place. Below is a program which contains a function isNumber() which returns true if the string passed to it is considered a number (integer). So 1984 us a number, but x24 is not. The program takes a word as input from the user (as an unbounded_string), and passes it to isNumber(). The function isNumber() converts the unbounded_string to a string, and then to an integer using integerβvalue(). If the conversion works, then the function returns true. If however, the conversion fails, then a Constraint_Error exception will be triggered, and false will be returned.
with ada.Text_IO; use Ada.Text_IO; with ada.Integer_Text_IO; use Ada.Integer_Text_IO; with ada.strings.unbounded; use ada.strings.unbounded; with ada.strings.unbounded.Text_IO; use ada.strings.unbounded.Text_IO; procedure number is aWord : unbounded_string; num: integer; function isNumber(s: unbounded_string) return boolean is temp: integer; begin temp := integer'value(to_String(s)); return true; exception when Constraint_Error => return false; end isNumber; begin put_line("Enter a word: "); get_line(aWord); if (isNumber(aWord)) then num := integer'value(to_String(aWord)); put(num); else put_line("Not a number"); end if; end number;
This sort of code could be used to count numbers in a document or something similar. You can use floatβvalue to do the same for floating-point numbers.
spqr