“It’s not nice to upset a Wookiee.”
— Han Solo
Wookiee’s are quite strong, and are known to rip people’s arms out of their sockets when provoked. In Ada, the role of the Wookiee is taken over by the exception. For those who have only ever coded in C, Ada is a bit of a culture shock. Partially because it won’t allow things that C-like languages do. And when it Ada doesn’t like something it’s like being whacked by a Wookiee.
Array goes out of bounds… WHACKED BY A WOOKIEE.
File doesn’t exist?… WHACKED BY A WOOKIEE.
But the reason people find exceptions challenging is because they, like a Wookiee can be somewhat if-your-face. Isn’t that a good thing? Here’s an example piece of Ada code which reads in 10 integers and print them in reverse:
with Ada.Text_IO, Ada.Integer_Text_IO; use Ada.Text_IO, Ada.Integer_Text_IO; procedure arrayRev is type intArray is array (1..10) of integer; Value : intArray; begin for i in 1..10 loop Get(Item => Value(i)); end loop; for i in reverse 1..11 loop Put(Item => Value(i)); New_Line; end loop; end arrayRev;
Now compile and run this code, entering the following numbers:
1 2 3 4 5 6 7 8 9 10 11 12
Ada will read the 12 numbers in fine, storing the first 10, and discarding the rest. The problem arises when the program attempts to access the 11th element of the array Value, which of course does not exist. Here is the “constraint” exception raised by Ada when this is attempted:
raised CONSTRAINT_ERROR : arrayrev.adb:12 index check failed
This indicates an index failed on Line 12 of the program, in the call to Put. Better still, see what happens when we attempt to enter a character in the input:
1 2 3 4 c 5 6 7 8 9
Ada does not like the fact that the letter “c” is not an integer, and raises an “IO” exception:
raised ADA.IO_EXCEPTIONS.DATA_ERROR : a-tiinio.adb:87 instantiated at a-inteio.ads:18
C would not allow both these things to happen quite happily. Ada won’t.