ZetCode

Tcl error handling

last modified November 24, 2026 Tcl 8.6

Tcl does not have a separate exception syntax. An error is a value that a command returns to the interpreter, and the interpreter decides whether that value becomes a normal result or an error condition. The error command raises one, catch intercepts one, and try adds structured handlers with cleanup. This article moves from the basic error call to custom error codes and a small validation routine.

The examples run in tclsh 8.6. Keeping errors as ordinary values means a procedure can pass a precise message, a machine readable code and a stack trace back to its caller without any special language support.

Raising an error with error

The error command stops the current script and reports a message. Its full form is error message ?info? ?code?. The optional info argument supplies the initial stack trace, and the optional code argument supplies the machine readable error code. Called with one argument, it uses the current call stack and the default code NONE.

raise_error.tcl
proc check_age {age} {
    if {![string is integer -strict $age]} {
        error "age must be an integer, got '$age'"
    }
    if {$age < 0 || $age > 130} {
        error "age out of range: $age"
    }
    return $age
}

puts "accepted: [check_age 42]"
puts "accepted: [check_age forty]"

The procedure validates its argument and returns it when it is acceptable. The second call cannot continue, so Tcl abandons the rest of the script. Note that the error is raised inside the procedure but the message names the bad value, which is what the caller needs to fix the problem. The first call has already printed its line before the failure.

Nothing catches the error, so tclsh prints the message and a trace to standard error and exits with status 1. The trace shows the failing error command, the procedure that contains it, and the caller.

$ tclsh raise_error.tcl
accepted: 42
age must be an integer, got 'forty'
    while executing
"error "age must be an integer, got '$age'""
    (procedure "check_age" line 3)
    invoked from within
"check_age forty"
    invoked from within
"puts "accepted: [check_age forty]""
    (file "raise_error.tcl" line 12)

catch and the result and options variables

The catch command evaluates a script and turns its outcome into a return code. Its form is catch script ?resultVar? ?optionsVar?. The result variable receives the normal result or the error message, and the options variable receives a dictionary describing the outcome. The Tcl catch command page lists the details; the return codes are 0 for success, 1 for an error, 2 for return, 3 for break and 4 for continue.

catch_result.tcl
proc check_age {age} {
    if {![string is integer -strict $age]} {
        error "age must be an integer, got '$age'"
    }
    return $age
}

set code [catch {check_age forty} result options]

puts "code:   $code"
puts "result: $result"
puts "keys:   [lsort [dict keys $options]]"
puts "--- errorinfo ---"
puts [dict get $options -errorinfo]

The braced script is evaluated by catch, not by the outer interpreter, so the call is protected. A code of 1 means an error, and the message lands in result. The options dictionary holds the same information in named fields, which is more convenient than parsing the trace. The script prints the keys so you can see what Tcl 8.6 provides.

$ tclsh catch_result.tcl
code:   1
result: age must be an integer, got 'forty'
keys:   -code -errorcode -errorinfo -errorline -errorstack -level
--- errorinfo ---
age must be an integer, got 'forty'
    while executing
"error "age must be an integer, got '$age'""
    (procedure "check_age" line 3)
    invoked from within
"check_age forty"

The options dictionary

Five fields of the options dictionary matter in daily work. -code repeats the return code, -level counts how many procedure levels the code should travel, -errorcode is a list that identifies the error, -errorinfo is the human readable trace, and -errorstack is the same trace in a machine readable form. The dictionary also carries -errorline, the line number of the failing command. The next script raises an error with a custom code and prints each field.

options.tcl
proc divide {a b} {
    if {$b == 0} {
        return -code error -errorcode {ARITH DIVZERO} \
            "cannot divide $a by zero"
    }
    return [expr {$a / $b}]
}

catch {divide 7 0} message options

puts "message:   $message"
puts "code:      [dict get $options -code]"
puts "level:     [dict get $options -level]"
puts "errorcode: [dict get $options -errorcode]"
puts "errorline: [dict get $options -errorline]"
puts "errorstack: [dict get $options -errorstack]"

return -code error raises an error from inside the procedure while still letting the procedure return normally in the success case. The -errorcode option attaches a two word code. The level is 0 because the error is not propagated through any additional procedure levels. The error line is 1 because it is relative to the script that catch evaluated.

The -errorstack value alternates a frame type and a frame description. INNER marks the innermost frame where the error was raised and CALL marks its callers. It is intended for debuggers and log collectors, while -errorinfo is the text a human reads.

$ tclsh options.tcl
message:   cannot divide 7 by zero
code:      1
level:     0
errorcode: ARITH DIVZERO
errorline: 1
errorstack: INNER {invokeStk1 divide 7 0}

try with on error and trap

The try command groups a body with handlers. Its shape is try body ?on code variableList handlerBody ...? ?trap pattern variableList handlerBody ...? ?finally cleanupBody?. An on clause matches a return code such as error or ok, while a trap clause matches a prefix of the error code list. The handler receives the message and the options dictionary as two variables.

try_trap.tcl
proc divide {a b} {
    if {$b == 0} {
        return -code error -errorcode {ARITH DIVZERO} \
            "cannot divide $a by zero"
    }
    return [expr {$a / $b}]
}

try {
    puts "10 / 2 = [divide 10 2]"
    puts "9 / 0  = [divide 9 0]"
} trap {ARITH DIVZERO} {message options} {
    puts "trapped: $message"
} on error {message options} {
    puts "other error: $message"
}

puts "still running"

The first line of the body succeeds and prints its result. The second line raises an error whose code starts with ARITH DIVZERO, so the trap handler runs and the on error handler is skipped. Because the handler itself completes normally, execution resumes after the try block. The pattern may be shorter than the code, so trap {ARITH} would catch every arithmetic error.

$ tclsh try_trap.tcl
10 / 2 = 5
trapped: cannot divide 9 by zero
still running

throw and custom error codes

The throw command is a shorter way to raise an error with a code: throw code message is equivalent to return -code error -errorcode code message. The code is a Tcl list, so it can carry a category and a detail, for example {BANK INSUFFICIENT_FUNDS}. By convention the first element is uppercase and names the subsystem.

custom_error_codes.tcl
proc withdraw {account amount} {
    set balance [dict get $account balance]
    if {$amount > $balance} {
        throw {BANK INSUFFICIENT_FUNDS} \
            "cannot withdraw $amount, balance is $balance"
    }
    dict set account balance [expr {$balance - $amount}]
    return $account
}

set account {owner Jane balance 120}

try {
    set account [withdraw $account 500]
} trap {BANK} {message options} {
    puts "bank error: $message"
    puts "code:       [dict get $options -errorcode]"
}

set account [withdraw $account 20]
puts "new balance: [dict get $account balance]"

The failed withdrawal is trapped by the broad BANK prefix, and the handler reads the full code from the options dictionary. The assignment inside the try body does not happen because the command fails. The second call succeeds and returns a new dictionary, which replaces the old account. This pattern keeps business errors separate from programming errors such as a missing dictionary key.

$ tclsh custom_error_codes.tcl
bank error: cannot withdraw 500, balance is 120
code:       BANK INSUFFICIENT_FUNDS
new balance: 100

finally and cleanup

A finally clause runs whether the body succeeds, raises an error or returns early. It is the place for releasing a resource, closing a channel or deleting a temporary file. The result of the body is preserved unless the cleanup script itself raises an error or returns a value.

finally_cleanup.tcl
proc process {values} {
    set total 0
    try {
        foreach v $values {
            if {![string is integer -strict $v]} {
                error "not an integer: $v"
            }
            incr total $v
        }
        return $total
    } finally {
        puts "cleanup after processing [llength $values] values"
    }
}

puts "total: [process {1 2 3}]"
puts "code:  [catch {process {1 x 3}} message]"
puts "error: $message"

The success path returns the sum, and the cleanup message appears before the caller prints the total. The failure path reaches the invalid value, raises an error, and still runs the same cleanup. The error then continues to the catch in the main script, which reports code 1.

$ tclsh finally_cleanup.tcl
cleanup after processing 3 values
total: 6
cleanup after processing 3 values
code:  1
error: not an integer: x

Rethrowing an error

A procedure often wants to add context to an error without losing the code the lower layer produced. The on error handler can modify the message and then pass the original options dictionary back with return -options. That keeps -errorcode and the original trace, so a caller can still react to the specific failure.

rethrow.tcl
proc read_settings {path} {
    if {![string match *.conf $path]} {
        throw {CONFIG BADNAME} "not a configuration file: $path"
    }
    return "settings from $path"
}

proc start_app {path} {
    try {
        return [read_settings $path]
    } on error {message options} {
        return -options $options "startup failed: $message"
    }
}

puts [start_app app.conf]
puts "code: [catch {start_app app.ini} message options]"
puts $message
puts "errorcode: [dict get $options -errorcode]"
puts "--- errorinfo ---"
puts [dict get $options -errorinfo]

The caller sees the prefixed message, but the code is still CONFIG BADNAME. The trace is the original one: Tcl reuses the -errorinfo value stored in the dictionary, so the prefix does not appear at the top of the trace. That is useful because the trace points at the real origin of the problem inside read_settings, while the message explains which operation was being attempted.

$ tclsh rethrow.tcl
settings from app.conf
code: 1
startup failed: not a configuration file: app.ini
errorcode: CONFIG BADNAME
--- errorinfo ---
not a configuration file: app.ini
    while executing
"throw {CONFIG BADNAME} "not a configuration file: $path""
    (procedure "read_settings" line 3)
    invoked from within
"read_settings $path"
    (procedure "start_app" line 3)
    invoked from within
"start_app app.ini"

A validation example

Form validation usually produces several problems at once. A practical approach is to collect every problem in a list and raise a single error at the end, with all messages joined. The caller then traps the validation code once instead of checking many separate return values. The next script validates a small list of dictionaries.

validate.tcl
proc validate_user {user} {
    set problems {}

    set name [dict get $user name]
    if {[string length $name] < 2} {
        lappend problems "name must have at least 2 characters"
    }

    set age [dict get $user age]
    if {![string is integer -strict $age]} {
        lappend problems "age must be an integer"
    } elseif {$age < 18} {
        lappend problems "age must be at least 18"
    }

    set email [dict get $user email]
    if {[string first @ $email] < 1} {
        lappend problems "email must contain @"
    }

    if {[llength $problems] > 0} {
        throw {VALIDATION FAILED} [join $problems "; "]
    }
    return "accepted $name"
}

set users {
    {name Jane age 34 email jane@example.com}
    {name J age 34 email jane@example.com}
    {name Bob age old email bob@example.com}
    {name Ann age 16 email ann@example.com}
}

foreach user $users {
    if {[catch {validate_user $user} result options]} {
        puts "rejected: $result"
        puts "  code: [dict get $options -errorcode]"
    } else {
        puts $result
    }
}

Each check appends a sentence and does not stop the procedure, so one run can report every problem with the record. The final throw uses a single code for all validation failures; the message carries the details. The main loop treats a nonzero catch result as a rejection and prints the code, which a graphical interface could use to highlight the offending fields.

$ tclsh validate.tcl
accepted Jane
rejected: name must have at least 2 characters
  code: VALIDATION FAILED
rejected: age must be an integer
  code: VALIDATION FAILED
rejected: age must be at least 18
  code: VALIDATION FAILED

Source

The Tcl 8.6 manual documents the commands used in this article. Start with error and catch for the basic mechanism, then read the try and return pages for handlers and options.

This article raised errors with error and throw, inspected the return codes and options of catch, and used try with trap, on error and finally. The Tcl error command and Tcl try command pages cover the individual commands, and Tcl regular expressions shows how to validate the text that reaches these checks.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.