Tcl catch Command

Catching Errors and Exceptions

Most programmers are familiar with the "catch" command to trap and manage errors. However, Tcl's catch command is more than just simple error handling by offering the information you can use to help "debug" your scripts.

catch command

The following code snippet demonstrates one of the ways to use a catch command in an if statement.

if { [ set returnCode [catch { command args } result returnOptions ]] } {
    # script error found
   } else {
        {
        # no script error

After evaluating a script, the returnCode, result, and returnOptions variables contain the return code, result, and a dictionary of return options, respectively. The dictionary will always include a -code and -level entry.

Scripts generating an error yield a return code of 1 (TCL_ERROR) and assign an error message to the result variable. For scripts yielding a return code of 0 (TCL_OK), the result variable contains the return value.

Tcl's return and catch commands are inextricably intertwined. Possible script return include: 0 (TCL_OK), 1 (TCL_ERROR), 2 (TCL_RETURN), 3 (TCL_BREAK), 4 (TCL_CONTINUE). Note that return codes other than those stated here may also be returned by a given script as the Tcl return command can take several forms: return return result return -code code result return return options value result

For more details on the catch and return commands, visit tcl.tk catch command and tcl.tk return command pages respectively.

Tcl catch command example: if expression

    if { [set returnCode [catch { script args } result returnOptions]] } {
        # Error! - Show contents of variables after catch.
        puts "Error ($returnCode) connecting to broker:  $result"
        # returnOptions includes:  -errorinfo, -errorcode, -errorline, and -errorstack
        dict for { returnOption returnValue } $returnOptions {
            puts "${returnOption}: $returnValue"
       # ... actions required to handle the error ...
        }
    } else {
        # Success! - Show contents of variables after catch.
        # The following statements are for debugging or 
        # information ONLY.  Comment them if not required.
        puts "$returnCode - $result"
        puts for { returnOption returnValue } $returnOptions {
            puts "${returnOption}: $returnValue"
        }
    }

Other Error Handling Options:

Other methods to trap and process errors and exceptions include try / finally.

We could also set a variable to capture the return code of a given command or script and act on it accordingly.

We'll discuss these options in a future post.

Did you find this article valuable?

Support Redge Shepherd by becoming a sponsor. Any amount is appreciated!