Condition handler

From Computer History Wiki
Revision as of 17:03, 21 October 2017 by Jnc (talk | contribs) (A pretty good start)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

A condition handler (sometimes exception handler) refers to a mechanism in some programming languages which allows the programmer to provide code to handle the occurrence of a condition.

When such an event (be it caused by some sort of hardware-detected issue, e.g. 'divide by zero', or purely software, e.g. 'unexpected end-of-file') happens, program execution is diverted to an condition handler for that specific condition, which is expected to deal with it.

In procedural languages (such as ALGOL and C - although neither one normally supports condition handlers), each procedure can set up one or more condition handlers on entry to an instance of the procedure. From then on, until that instance exits, any time that condition is signalled (in either that procedure, or any procedure it calls, and so on), execution jumps to that condition handler.

Should an inferior procedure set up a condition handler for that same condition, the inferior procedure's handler will be invoked preferentially. Information about active condition handlers is generally maintained in the call stack, so that handlers are automatically discarded when a procedure instance that set them up exits. When looking for a handler for a signalled condition, the condition system starts at the bottom of the call stack, and works its way upwards, looking for an active handler for rhat condition.

Condition handlers are usually provided with a number of ways to terminate their execution; they may (after repairing the condition that led to the signalling of the condition) resume operation at the place where the condition was signalled; they may re-signal the condition to a higher-level handler for that condition; they may signal another condition; or they may terminate the program (if the problem cannot be repaired).

Special conditions

In addition to the above, there are a variety of special operations.

If no condition handler for a particular signalled condition is found in the call stack, the condition system may respond by signalling an 'unhandled condition' condition. Usually a handler for this condition is provided in the top-level procedure, to catch otherwise un-handled conditions.

An unwind protect is a special condition handler which, if set up in any procedure on the call stack, if the call stack has to be unwound to get to a handler for a particular signalled condition, for any procedure invocation which is unwound which has a handler for 'unwind protect', that handler is called 'on the way through'. This allows that instance to do any cleanup it needs to, before it is terminated by the condition system.