Section 10.1 - Exception Basics

Errors and other exceptional situations must be handled by programs that work in the real world. Ada provides facilities to deal with these real problems which make handling them much easier. In Ada, an exception represents a kind of exceptional situation, usually a serious error. At run-time an exception can be raised, which calls attention to the fact that an exceptional situation has occurred.

The default action when an exception is raised is to halt the program. Usually the program will print out the name of the exception and where the problem took place, though this depends on your compiler. The next few sections will show how to override this default.

If you don't want to halt the program, you'll need to tell Ada what to do instead by defining an exception handler. An exception handler states what exceptions to handle and what to do when a given exception is raised.

Exceptions generally represent something unusual and not normally expected - reserve their use for things like serious error conditions. They shouldn't be used for ``expected'' situations, because they can be slower and if incorrectly handled can stop a program. The place where an exception is raised may be far away from where it is handled, and that makes programs with a voluminous number of different exceptions harder to understand. Instead, exceptions should be used when a subprogram cannot perform its job for some significant reason.

Ada has a number of predefined exceptions that are raised when certain language-defined checks fail. The predefined check you're most likely to see is Constraint_Error; this exception is raised when a value goes out-of-bounds for its type. Examples of this include trying to store a value that's too large or too small into that type, dividing by zero, or using an invalid array index.

Naturally, there is some run-time overhead in performing all these checks, though less than you might think. It is possible to suppress these language-defined checks; this should only be done after the program is thoroughly debugged, and many people think that it shouldn't be done even then.

Some packages define their own exceptions, for example, Text_IO defines the exception End_Error that is raised when you attempt to ``Get'' something after you've reached the end of the file, and Name_Error is raised if try to open a file that doesn't exist.

In the next few sections we'll learn how to define exceptions, how to raise exceptions, and how to handle exceptions.


If you're defining a package that displays the view from an airplane cockpit, should you raise an exception whenever the view changes from daytime to nighttime?

  1. You should probably raise an exception.
  2. You should probably not raise an exception.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 10 outline

David A. Wheeler (

The master copy of this file is at "".