In order to handle an exception, you need to write an exception handler (naturally!).
We illustrate the mechanism by first looking at how to define an exception handler for a given subprogram.
Then we look at the general mechanism for handling exceptions at any given point in a program.
General form:
subprogram specification declarations begin statements exception one or more exception handlers end;
Operation:
An example procedure just reads a file name from a user and then opens that file. An exception handler is provided to cope with the various things that might go wrong when opening the file.
You can define your own block at any point in an Ada program.
Its structure is similar to a subprogram:
declare declarations begin statements exception exception handlers end;
The declarations and exception handler are optional.
One reason for defining a block statement is to declare some very localised variables.
Sometimes you only want a variable to exist for few statements. Rather than defining a separate procedure, or defining a variable that is visible right throughout a large procedure, you can use a declare block to limit the scope of a variable:
procedure main is x,y : integer; begin statements; -- time to swap two variables declare temp : integer; begin temp := x; x := y; y := temp; end; more statements end;
The local declarations are only known inside the block statement.
The other reason for defining a block statement is to enable local exception handling (especially in a loop).
Operation:
An example program shows how input can be done inside a loop, with an exception handler to take care of problems, so that it can be guaranteed that acceptable input is eventually provided.