Modula-2 error handling
last modified November 27, 2026 Modula-2
Wirth's Modula-2 had no exceptions: a runtime error ended the program, and
procedures reported failures through return values and VAR
parameters, as ToInt does in the
reading input article. ISO Modula-2
added exception handling to the language. A procedure or a module body may
end with an EXCEPT part that runs when an exception is raised,
the RETRY statement runs the body again, and a module may have a
FINALLY part that runs when the program ends. The library
modules M2EXCEPTION and EXCEPTIONS identify
exceptions and raise new ones.
All examples are compiled with -fiso. Several also need
-fsoft-check-all, for reasons the first sections explain.
A runtime error
A runtime error stops a program at once. The operators article showed it for an integer division by zero; here the same error comes from a procedure.
MODULE average;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
PROCEDURE Average(sum, count: INTEGER): INTEGER;
BEGIN
RETURN sum DIV count
END Average;
BEGIN
WriteString("average of 3 values: ");
WriteInt(Average(247, 3), 0); WriteLn;
WriteString("average of 0 values: ");
WriteInt(Average(0, 0), 0); WriteLn;
WriteString("done"); WriteLn
END average.
The second call divides by zero. The program stops in the middle of the
line, prints a message to the error output and exits with status 134, the
status of a program that ends with the C function abort. The
last line is never printed. The default build names only the place in the
runtime library that detected the error. Compiled with
-fsoft-check-all, the program checks the divisor itself before
the division, and the message names the source file, the line, the column,
the procedure and the variable.
$ gm2 -fiso average.mod -o average $ ./average average of 3 values: 82 average of 0 values: RTExceptions.mod:686:35: In wholediv RTExceptions.mod:686:35:illegal whole value exception $ echo $? 134 $ gm2 -fiso -fsoft-check-all average.mod -o average $ ./average average of 3 values: 82 average of 0 values: average.mod:7:10: In procedure Average average.mod:7:10:this division expression ‘count’ will cause an exception as the divisor is zero $ echo $? 134
Runtime checks
Division by zero is caught in every build, because the processor traps it.
Most other errors are not: an array index out of bounds, a value outside a
subrange or an overflowing CARDINAL go unnoticed unless the
compiler inserts checks.
MODULE bounds;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
marks: ARRAY [1..5] OF INTEGER;
i: INTEGER;
BEGIN
FOR i := 1 TO 6 DO
marks[i] := i * 10
END;
WriteString("last mark: "); WriteInt(marks[5], 0); WriteLn
END bounds.
The loop writes six marks into an array of five. The default build runs to
the end, writes past the array and exits with status 0, a silent error that
could corrupt another variable. -fsoft-check-all turns on all
runtime checks: indexes, subranges, whole-number overflow, division,
NIL pointers, CASE without a matching label and
functions that end without RETURN. The checked build stops at
the sixth assignment. The checks cost some speed; the
compiling and debugging
article measures how much and shows how to turn them on one by one.
$ gm2 -fiso bounds.mod -o bounds $ ./bounds last mark: 50 $ echo $? 0 $ gm2 -fiso -fsoft-check-all bounds.mod -o bounds $ ./bounds bounds.mod:11:12: In program module bounds bounds.mod:11:12:if this access to the static array is ever made then the index will be out of bounds in the 1st array subscript $ echo $? 134
Catching an exception
In ISO Modula-2 a runtime error raises an exception. A procedure catches
it in an EXCEPT part, written after the statements of the
body and before the final END.
MODULE handler;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
PROCEDURE Average(sum, count: INTEGER): INTEGER;
BEGIN
RETURN sum DIV count
EXCEPT
WriteString("(no values) ");
RETURN 0
END Average;
BEGIN
WriteString("average of 3 values: ");
WriteInt(Average(247, 3), 0); WriteLn;
WriteString("average of 0 values: ");
WriteInt(Average(0, 0), 0); WriteLn;
WriteString("done"); WriteLn
END handler.
When the division fails, control leaves the body and enters the
EXCEPT part. The handler prints a note and returns 0, and the
program continues as if Average had returned normally. Without
-fsoft-check-all the handler is never reached: the processor
trap goes to the runtime library, which stops the program. A handler for a
runtime error therefore needs the checks, which raise the exception before
the faulty operation runs.
$ gm2 -fiso handler.mod -o handler $ ./handler average of 3 values: 82 average of 0 values: RTExceptions.mod:686:35: In wholediv RTExceptions.mod:686:35:illegal whole value exception $ echo $? 134 $ gm2 -fiso -fsoft-check-all handler.mod -o handler $ ./handler average of 3 values: 82 average of 0 values: (no values) 0 done $ echo $? 0
Which exception was raised
Errors detected by the language are called language exceptions. The ISO
module M2EXCEPTION lists them in the enumeration
M2Exceptions; M2Exception returns the one being
handled, and IsM2Exception tells whether the current exception
is a language exception at all.
MODULE kinds;
FROM STextIO IMPORT WriteString, WriteLn;
FROM M2EXCEPTION IMPORT M2Exceptions, M2Exception, IsM2Exception;
TYPE
Month = [1..12];
VAR
zero, big: INTEGER;
PROCEDURE Try(test: CARDINAL);
VAR
a: ARRAY [0..3] OF INTEGER;
m: Month;
n: INTEGER;
BEGIN
CASE test OF
1: a[test + 3] := 1
| 2: m := big
| 3: n := big DIV zero
| 4: n := MAX(INTEGER); n := n + big
| 5: CASE big OF 1: n := 1 | 2: n := 2 END
END;
WriteString("no exception"); WriteLn
EXCEPT
IF IsM2Exception() THEN
CASE M2Exception() OF
indexException: WriteString("index out of bounds")
| rangeException: WriteString("value out of range")
| wholeDivException: WriteString("division by zero")
| wholeValueException: WriteString("whole number overflow")
| caseSelectException: WriteString("no CASE label matched")
ELSE
WriteString("another language exception")
END;
WriteLn;
RETURN
END
END Try;
VAR
i: CARDINAL;
BEGIN
zero := 0;
big := 13;
FOR i := 1 TO 5 DO
Try(i)
END
END kinds.
Try provokes a different error for each test: an index of 4
in an array of four elements, the value 13 in a variable of type
[1..12], a division by zero, an INTEGER overflow
and a CASE whose selector matches no label. The handler reports
the kind and returns, so the loop goes on with the next test. Any other
exception reaches the end of the handler and goes on to the caller, as the
next sections show. The other
values of M2Exceptions include invalidLocation
for a NIL pointer, functionException for a
function that ends without RETURN and
realValueException for a real overflow.
$ gm2 -fiso -fsoft-check-all kinds.mod -o kinds $ ./kinds index out of bounds value out of range division by zero whole number overflow no CASE label matched
Propagation
An exception does not have to be handled where it is raised. If the
procedure has no EXCEPT part, the exception leaves it and
passes to the caller, and from there to its caller, until a handler is
found.
MODULE propagate;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
prices: ARRAY [0..4] OF INTEGER;
PROCEDURE Price(item: CARDINAL): INTEGER;
BEGIN
RETURN prices[item]
END Price;
PROCEDURE Total(first, last: CARDINAL): INTEGER;
VAR
i: CARDINAL;
sum: INTEGER;
BEGIN
sum := 0;
FOR i := first TO last DO
sum := sum + Price(i)
END;
RETURN sum
END Total;
PROCEDURE Report(first, last: CARDINAL);
BEGIN
WriteString("total: ");
WriteInt(Total(first, last), 0); WriteLn
EXCEPT
WriteString("no such item"); WriteLn;
RETURN
END Report;
BEGIN
prices[0] := 12; prices[1] := 7; prices[2] := 30;
prices[3] := 5; prices[4] := 18;
Report(0, 4);
Report(2, 6);
WriteString("done"); WriteLn
END propagate.
The bad index is used in Price, two calls below
Report. Neither Price nor Total has
a handler, so both are left at once and the handler of Report
runs. The partial sum in Total is lost, and
total:, already printed, stays on the line. Error handling
belongs where the program can do something sensible about the error, which
is often several calls above the place where it occurs.
$ gm2 -fiso -fsoft-check-all propagate.mod -o propagate $ ./propagate total: 72 total: no such item done
Ending a handler
A handler decides what happens next. RETURN ends the
procedure normally and marks the exception as handled. A handler that
reaches its END without RETURN raises the same
exception again in the caller.
MODULE reraise;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
PROCEDURE Ratio(a, b: INTEGER): INTEGER;
BEGIN
RETURN a DIV b
EXCEPT
WriteString("Ratio failed for ");
WriteInt(a, 0); WriteString(" and "); WriteInt(b, 0); WriteLn
END Ratio;
PROCEDURE Show(a, b: INTEGER);
BEGIN
WriteInt(Ratio(a, b), 0); WriteLn
EXCEPT
WriteString("Show caught it"); WriteLn;
RETURN
END Show;
BEGIN
Show(9, 4);
Show(9, 0);
WriteInt(Ratio(1, 0), 0); WriteLn;
WriteString("not reached"); WriteLn
END reraise.
The handler in Ratio only reports the arguments; it has no
value to return. The exception goes on to Show, which handles
it. The third call comes from the module body, which has no handler, so the
program stops with the original message. The message is glued to the
report because the ISO output channel holds back the last line mark until
the next output, as the console
output article explains. A function procedure that catches an exception
must either return a value or let the exception go on.
$ gm2 -fiso -fsoft-check-all reraise.mod -o reraise $ ./reraise 2 Ratio failed for 9 and 0 Show caught it Ratio failed for 1 and 0reraise.mod:7:10: In procedure Ratio reraise.mod:7:10:this division expression ‘b’ will cause an exception as the divisor is zero $ echo $? 134
Raising an exception
A program raises its own exceptions with the EXCEPTIONS
module. AllocateSource creates an exception source, a value
that identifies the part of the program that raises the exception.
RAISE takes the source, a number and a message.
MODULE raise;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM EXCEPTIONS IMPORT ExceptionSource, AllocateSource, RAISE,
IsCurrentSource, CurrentNumber;
CONST
notPositive = 1;
tooLarge = 2;
VAR
account: ExceptionSource;
balance: INTEGER;
PROCEDURE Withdraw(amount: INTEGER);
BEGIN
IF amount <= 0 THEN
RAISE(account, notPositive, "amount must be positive")
END;
IF amount > balance THEN
RAISE(account, tooLarge, "insufficient funds")
END;
balance := balance - amount
END Withdraw;
PROCEDURE Try(amount: INTEGER);
BEGIN
Withdraw(amount);
WriteString("withdrew "); WriteInt(amount, 0);
WriteString(", balance "); WriteInt(balance, 0); WriteLn
EXCEPT
IF IsCurrentSource(account) THEN
CASE CurrentNumber(account) OF
notPositive: WriteString("refused: not a positive amount")
| tooLarge: WriteString("refused: balance is only ");
WriteInt(balance, 0)
END;
WriteLn;
RETURN
END
END Try;
BEGIN
AllocateSource(account);
balance := 100;
Try(30);
Try(-5);
Try(500);
Try(70);
Withdraw(1)
END raise.
Withdraw raises an exception with number 1 for an amount that
is not positive and number 2 for an amount larger than the balance. The
handler in Try checks with IsCurrentSource that
the exception comes from the account, and CurrentNumber
returns its number. An exception from another source would reach the end
of the handler and go on to the caller. The last withdrawal is not
guarded, and the uncaught exception ends the program with its message and
status 134. User exceptions do not need -fsoft-check-all.
$ gm2 -fiso raise.mod -o raise $ ./raise withdrew 30, balance 70 refused: not a positive amount refused: balance is only 70 withdrew 70, balance 0EXCEPTIONS.mod:65:56: In RAISE EXCEPTIONS.mod:65:56:insufficient funds $ echo $? 134
The message
GetMessage copies the message of the current exception into
a character array. Outside a handler it returns an empty string.
MODULE message;
FROM STextIO IMPORT WriteString, WriteLn;
FROM EXCEPTIONS IMPORT ExceptionSource, AllocateSource, RAISE, GetMessage;
VAR
parser: ExceptionSource;
PROCEDURE Parse(s: ARRAY OF CHAR);
BEGIN
IF s[0] = 0C THEN
RAISE(parser, 1, "empty input")
END;
WriteString("parsed "); WriteString(s); WriteLn
END Parse;
PROCEDURE Try(s: ARRAY OF CHAR);
VAR
text: ARRAY [0..255] OF CHAR;
BEGIN
Parse(s)
EXCEPT
GetMessage(text);
WriteString("message: ["); WriteString(text); WriteString("]"); WriteLn;
RETURN
END Try;
BEGIN
AllocateSource(parser);
Try("3 + 4");
Try("")
END message.
gm2 15.2 stores the message with two lines in front of it: the place in
the library module EXCEPTIONS.mod where the exception was
raised, followed by a line break. The text passed to RAISE
comes after that position on the second line, and a line break ends it.
The position is the same for every user exception, so it says nothing
about the program; a handler that needs to tell the user what went wrong
uses CurrentNumber and its own messages, as the previous
example does.
$ gm2 -fiso message.mod -o message $ ./message parsed 3 + 4 message: [EXCEPTIONS.mod:65:56: In RAISE EXCEPTIONS.mod:65:56:empty input ]
Trying again
RETRY in a handler marks the exception as handled and runs
the body of the procedure again from the start. It suits errors that the
user can correct, such as bad input. The example reads the input with
ToInt from the Numbers module of the reading
input article.
MODULE retry;
FROM STextIO IMPORT WriteString, WriteLn, ReadString, SkipLine;
FROM SWholeIO IMPORT WriteInt;
FROM EXCEPTIONS IMPORT ExceptionSource, AllocateSource, RAISE,
IsCurrentSource;
FROM Numbers IMPORT ToInt;
CONST
MaxAttempts = 3;
VAR
input: ExceptionSource;
attempts: CARDINAL;
PROCEDURE ReadAge(): INTEGER;
VAR
line: ARRAY [0..79] OF CHAR;
age: INTEGER;
BEGIN
INC(attempts);
WriteString("age: ");
ReadString(line);
SkipLine;
IF NOT ToInt(line, age) THEN
RAISE(input, 1, "not a number")
END;
IF (age < 0) OR (age > 150) THEN
RAISE(input, 2, "age out of range")
END;
RETURN age
EXCEPT
IF IsCurrentSource(input) AND (attempts < MaxAttempts) THEN
WriteString("enter a whole number from 0 to 150"); WriteLn;
RETRY
END
END ReadAge;
VAR
answer: INTEGER;
BEGIN
AllocateSource(input);
attempts := 0;
answer := ReadAge();
WriteString("in ten years you will be ");
WriteInt(answer + 10, 0); WriteLn
END retry.
ReadAge raises an exception for a line that is not a number
and for an age out of range. The handler retries up to three attempts.
The local variables keep their values across a retry, but the body runs
again from its first statement, so a counter initialised in the body would
start again at zero; attempts is therefore a module variable.
After the third failure the handler ends without RETRY or
RETURN, and the exception stops the program.
$ gm2 -fiso -c Numbers.mod $ gm2 -fiso retry.mod Numbers.o -o retry $ ./retry age: abc enter a whole number from 0 to 150 age: 200 enter a whole number from 0 to 150 age: 42 in ten years you will be 52 $ ./retry age: x enter a whole number from 0 to 150 age: -1 enter a whole number from 0 to 150 age: old EXCEPTIONS.mod:65:56: In RAISE EXCEPTIONS.mod:65:56:not a number
Finalisation
A module body may end with a FINALLY part. It runs when the
program terminates, after the program body, and suits clean-up work such as
closing a file or printing a summary.
DEFINITION MODULE Log; PROCEDURE Note(text: ARRAY OF CHAR); END Log.
IMPLEMENTATION MODULE Log;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
count: CARDINAL;
PROCEDURE Note(text: ARRAY OF CHAR);
BEGIN
INC(count);
WriteString("log: "); WriteString(text); WriteLn
END Note;
BEGIN
count := 0
FINALLY
WriteString("log closed after ");
WriteCard(count, 0); WriteString(" notes"); WriteLn
END Log.
Log counts its notes. The BEGIN part sets the
counter when the program starts, and the FINALLY part reports
it when the program ends; no client has to call a closing procedure.
MODULE finally;
FROM Log IMPORT Note;
BEGIN
Note("loading");
Note("checking");
Note("saving")
END finally.
finally writes three notes and ends normally.
status writes two notes and stops with HALT(2),
as a program does when its input is missing.
MODULE status;
FROM Log IMPORT Note;
BEGIN
Note("loading");
Note("input is missing");
HALT(2)
END status.
The final line comes from the FINALLY part of
Log, after the program body has finished. In gm2 15.2 the
FINALLY parts do not run when the program ends with an
uncaught exception, and they do not run after HALT(n) either:
the second program stops with status 2, and the log is never closed.
$ gm2 -fiso -c Log.mod $ gm2 -fiso finally.mod Log.o -o finally $ ./finally log: loading log: checking log: saving log closed after 3 notes $ gm2 -fiso status.mod Log.o -o status $ ./status log: loading log: input is missing $ echo $? 2
A handler for the whole program
The body of the program module may have an EXCEPT part too.
It catches every exception that is not handled on the way, which makes it
the place for a last report and a meaningful exit status.
MODULE guard;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM M2EXCEPTION IMPORT IsM2Exception;
TYPE
Group = RECORD
total, count: INTEGER
END;
VAR
groups: ARRAY [1..4] OF Group;
done: CARDINAL;
average, status: INTEGER;
PROCEDURE Set(i: CARDINAL; total, count: INTEGER);
BEGIN
groups[i].total := total;
groups[i].count := count
END Set;
BEGIN
status := 0;
done := 0;
Set(1, 247, 3); Set(2, 160, 2); Set(3, 0, 0); Set(4, 90, 1);
WHILE done < 4 DO
average := groups[done + 1].total DIV groups[done + 1].count;
INC(done);
WriteString("group "); WriteCard(done, 0);
WriteString(": "); WriteInt(average, 0); WriteLn
END
EXCEPT
IF IsM2Exception() THEN
WriteString("error: bad data in group ")
ELSE
WriteString("error: unexpected exception in group ")
END;
WriteCard(done + 1, 0); WriteLn;
status := 1;
RETURN
FINALLY
WriteCard(done, 0); WriteString(" of 4 groups processed"); WriteLn;
HALT(status)
END guard.
The third group has no members, and the division raises an exception. The
handler of the module body reports the group and sets
status to 1. Its RETURN ends the body normally,
so the FINALLY part runs, prints how far the program got and
passes the status to the shell with HALT. Calling
HALT in the handler would skip the summary, because
HALT does not run the FINALLY parts.
$ gm2 -fiso -fsoft-check-all guard.mod -o guard $ ./guard group 1: 82 group 2: 80 error: bad data in group 3 2 of 4 groups processed $ echo $? 1
Source
Exception handling in GNU Modula-2
In this article we have seen runtime errors in the default and the checked
build, caught exceptions with EXCEPT, identified language
exceptions with M2EXCEPTION, followed an exception through
the callers, raised our own exceptions with EXCEPTIONS, read
input again with RETRY, cleaned up in FINALLY
and turned an exception into an exit status. The
environment and processes
article introduces HALT(n), and the
compiling and debugging
article finds errors with the compiler and the debugger.
Author
List all Modula-2 tutorials.