Section 10.3 - Handling Exceptions

As we've noted many times, if an exception is raised and isn't handled the program stops. To handle exceptions you must define, reasonably enough, an exception handler.

When an exception is raised (by the raise statement) Ada will abandon what it was doing and look for a matching exception handler in the sequence of statements where the exception was raised. A sequence of statements is the set of statements between the keywords "begin" and "end". If Ada doesn't find a match, it returns from the current subprogram (cleaning up along the way) and tries to find a matching exception handler in the caller (from where it was called). If it doesn't find one there, it exits that subprogram (cleaning up along the way) and tries yet again. Ada keeps repeating this process until it finds a matching exception handler or until it exits the program.

An exception handler is defined just before the "end" statement that matches a "begin" statement.

For example, here's a procedure that "Open"s a file if it can, and if the file doesn't exist it "Create"s it.

  procedure Open_Or_Create(File : in out File_Type;
                           Mode : File_Mode; Name : String) is
  begin
    -- Try to open the file. This will raise Name_Error if
    -- it doesn't exist.
    Open(File, Mode, Name);
  exception
    when Name_Error =>
      Create(File, Mode, Name);
  end Open_Or_Create;

Here's a simplified BNF of an exception handler:

  exception_handler ::= exception_choice { "|"  exception_choice } "=>"
                        sequence_of_statements
  exception_choice  ::= exception_name | "others"

The keyword "others" means all exceptions not explicitly listed in this exception handler; thus, you can handle all exceptions if you want to.

Inside an exception handler you can do any kind of processing you wish. If, after processing, you find you need to raise the same exception to a higher level, you can use the "raise" statement without the name of an exception. A raise statement without a named exception re-raises the exception being handled. Raise statements can only re-raise exceptions inside an exception handler.

You can pass information along with an exception, and there is a predefined package of exception-related operations. We won't go into that now, but if you're interested, you can examine section 11 of the Ada RM, which discusses exceptions.


There is no quiz question for this section.

You may go to the next section.


You may also:

PREVIOUS Go back to the previous section

OUTLINE  Go up to the outline of lesson 10

David A. Wheeler (dwheeler@dwheeler.com)

The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s10sf.htm".