• Define what an exception is
  • Define how exceptions are raised

An exception is a special signal that is raised by the code to indicate some unusual situation has occurred, typically some kind of error. The exception propagates up the call stack until it encounters an exception trap, which transfers control to the exception handler.

In Tcl, there are four predefined exceptions:

  • TCL_ERROR (1) — indicates an error condition occurred. Can be generated by error and throw (and return with the right options). Usually only caught by catch or try, or propagates to the event loop when it gets handed off to bgerror.
  • TCL_RETURN (2) — indicates that the current execution context (e.g., procedure call) is to finish with the value in the Tcl result as the result of the execution. Usually caught by the end of the execution context.
  • TCL_BREAK (3) — indicates that the current loop should finish. Usually caught by loops like while, for and foreach.
  • TCL_CONTINUE (4) — indicates that the current loop should begin its next iteration (first checking its termination condition). Usually caught by loops like while, for and foreach.

The following critical things should be noted about Tcl's exception handling:

  • TCL_OK (0) would also be an exception code, except that it represents the state where no exception processing is happening.
  • return can generate all kinds of exception.
  • catch traps all exceptions unless the interpreter is in an explicit unwinding state (e.g., because it is deleted). try is to be favoured in new code because it can be much more precise in what exceptions it handles.
  • You can define your own custom exceptions as small integers (formally, your platform's C ints, so typically 32-bit integers on current hardware). Use numbers larger than 4 or smaller than 0. Be aware that you should use these numbers consistently across the whole Tcl process (all interpreters, all threads) and that some parts of the Tcl core may assume that such values do not occur. Public library code should never define custom exceptions. If Tcl ever defines further exception codes, they will be larger than 0 (this is currently extremely unlikely, to be fair).
  • You are recommended to not use return to generate a break or continue; the real commands generate better bytecode.

See also