Exception Handling


General

Oz incorporates an exception handling mechanism which allows to safeguard program code against exceptional and/or unforeseeable situations at run-time, and also to raise and handle user-defined exceptions.

Exceptions

An exception is any expression E. To raise the exception E one executes the following statement (Example).

raise E end

Basic Syntax

The basic exception handling statement has the following format.

try S1 catch (P then S)* end

Execution of this statement is equivalent to executing S1 if S1 does not raise an exception. If S raises exception E and E matches one of the patterns P, control is passed to the corresponding handler clause S. (Example)

Finally Syntax

An exception handling statement may also specify code to be executed on normal as well as exceptional situations. This is supported through a finally clause as in:

try S1 catch (P then S)* finally S2 end

where (P then S)* means (P1 then S1 [] ... [] Pn then Sn).

A finally clause is typically desirable to safely terminate IO after an exception. (Example)

The precise semantics of this statement is explained in two steps. The statement

try S1 catch (P then S)* finally S2 end

is equivalent to

try (try S1 catch (P then S)* end) finally S2 end
where
try S1 finally S2 end

is equivalent to

local Exc in
  try S1 catch E then Exc=E end   S2 
  case {IsDet Exc} then raise Exc end else skip end
end

Concurrency

Exception handling is thread-wise. Concurrent threads escape their enclosing try-scope. For example
try thread S1 end S2 end
is equivalent to
thread S1 end 
try S2 end  

System Exceptions

The exceptions raised by the Oz system are records with one of the labels failure, error, and system.

The label failure indicates the attempt to add an inconsistent constraint to the store. The label error indicates a run-time error which should not occur. The label system indicates a run-time condition, i.e., an unforeseeable exceptional situation like a closed window.

The programmer is advised to use different labels for user-defined exceptions.

Note: The exact format of Oz system exceptions is in an experimental state and therefore remains underspecified.

Error Messages

When an exception is raised but not handled, an error message is printed (with one exception mentioned below). (Example)

Failure

When an exception labelled failure is raised in a space, this space is failed. (Example)

Formatting Error Messages

There is some support for formatting error messages corresponding to unhandled user-defined exceptions. This is described in the Standard Modules.

Concurrent Exception Handling

It is possible to raise an exception on another concurrent thread if the identity of this thread is known. This is also an experimental feature (Example).


Martin Müller