Error Handling & Events

36.1 No exceptions — but plenty of tools

ALGOL 68 has no exception mechanism. Errors are handled with:

Return values — status codes or BOOL results with REF out-parameters.

Unions — return either a value or an error description.

Non-local jumps — GOTO a label in an enclosing range, unwinding procedure calls.

Transput event routines — on logical file end, on value error, etc.

Run-time checks — a68g aborts with a diagnostic on subscript errors, NIL dereference, scope violations, overflow, uninitialized values, and division by zero.

36.2 Union results

BEGIN
   MODE ERR = STRUCT (INT code, STRING message);
   MODE RESULT = UNION (REAL, ERR);

   PROC safe sqrt = (REAL x) RESULT:
      IF x < 0 THEN ERR (1, "negative argument") ELSE sqrt(x) FI;

   PROC report = (RESULT r) VOID:
      CASE r IN
         (REAL v): print(("ok: ", fixed(v, 0, 4), newline)),
         (ERR e):  print(("error ", whole(code OF e, 0), ": ", message OF e, newline))
      ESAC;

   report(safe sqrt(2));
   report(safe sqrt(-4))
END

36.3 Non-local exits with GOTO

The jump from inside digit value (called from parse) unwinds both procedure calls.

BEGIN
   PROC digit value = (CHAR c) INT:
      IF c >= "0" AND c <= "9" THEN ABS c - ABS "0" ELSE GOTO bad input FI;

   PROC parse = (STRING s) INT:
   BEGIN
      INT n := 0;
      FOR i FROM LWB s TO UPB s DO n := n * 10 + digit value(s[i]) OD;
      n
   END;

   print((parse("1234") + 1, newline));
   print((parse("12x4"), newline));        # jumps to bad input #
   print(("not reached", newline));
   GOTO end of program;
bad input:
   print(("error: invalid digit", newline));
end of program: SKIP
END

36.4 Transput events

Each FILE has event routines of mode PROC (REF FILE) BOOL. If the routine returns TRUE, the condition is considered handled and transput continues; if FALSE, the default action (usually an error) happens. A routine can also jump out.

on logical file end reading past the end of the data on physical file end the physical medium is full/ends on page end, on line end layout boundaries are crossed on format end a format is exhausted on value error a value cannot be converted (e.g. letters when reading an INT) on char error an unexpected character is read on format error a value does not match a format pattern

on value error(stand in, (REF FILE f) BOOL: (print(("bad number", newline)); GOTO retry));

36.5 Debugging in a68g

Diagnostics include the source line and a description of the mode error or run-time fault.

--trace traces execution; --debug (or a monitor) lets you inspect the stack and variables after an error.

--check stops after syntax and mode checking — a fast way to find type errors.