Ada loves exceptions

One of the great things about Ada is it loves exceptions. Exceptions can be used to deal with issues that other languages (let’s call them “C”-ish) tend to ignore. Take for example the following piece of code which does nothing but read in a number… if a valid integer is entered, the program ends.  If something other than an integer is entered, say a character, then an exception is triggered, and the message in the exception part of the program is output, and the program loops to ask for input again. The function skip_line() jumps to the start of the next line (avoiding anything in the buffer).

If an error occurs during execution of get(), the exception Data_Error is raised in the block, and execution of statements in the block is abandoned. Control is then transferred to the Data_Error exception handler associated with the block. In this case, the exception handler displays an error message, then executes skip_line(), going back to the next iteration of the loop. Data_Error is propagated if the input character sequence to get() does not belong to the range of the required subtype.

Fun eh? But certainly easy.

with Ada.Text_IO; use Ada.Text_IO;
with ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Xcept is
    n : integer;
        put("Enter a number: ");
        when Data_Error => put_line("Invalid number.");
    end loop;
end Xcept;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.