Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 6.  Control Structure Commands


The error command raises an error condition that terminates a script unless it is trapped with the catch command. The command takes up to three arguments:

error message ?info? ?code?

The message becomes the error message stored in the result variable of the catch command.

If the info argument is provided, then the Tcl interpreter uses this to initialize the errorInfo global variable. That variable is used to collect a stack trace from the point of the error. If the info argument is not provided, then the error command itself is used to initialize the errorInfo trace.

Example 6-17 Raising an error.
proc foo {} {
   error bogus
=> bogus
set errorInfo
=> bogus
   while executing
"error bogus"
    (procedure "foo" line 2)
    invoked from within

In the previous example, the error command itself appears in the trace. One common use of the info argument is to preserve the errorInfo that is available after a catch. In the next example, the information from the original error is preserved:

Example 6-18 Preserving errorInfo when calling error.
if {[catch {foo}result]} {
   global errorInfo
   set savedInfo $errorInfo
   # Attempt to handle the error here, but cannot...
   error $result $savedInfo

The code argument specifies a concise, machine-readable description of the error. It is stored into the global errorCode variable. It defaults to NONE. Many of the file system commands return an errorCode that has three elements: POSIX, the error name (e.g., ENOENT), and the associated error message:

POSIX ENOENT {No such file or directory}

In addition, your application can define error codes of its own. Catch phrases can examine the code in the global errorCode variable and decide how to respond to the error.

      Previous section   Next section