Errors

An error in Tcl stops the script and goes up through each caller, until a catch or a try stops it. An error has a message and an error code: a list that code can match. This lesson makes add check its input.

Give an error

The box gives add two checks. Each error has a code that starts with JOT, so that a caller can tell the errors of jot from other errors.

proc add {text} {
    global notes
    if {[string trim $text] eq ""} {
        return -code error -errorcode {JOT EMPTY} "a note needs text"
    }
    if {[string length $text] > 80} {
        throw {JOT LONG} "a note has 80 characters at most"
    }
    lappend notes [dict create text $text done 0]
    return [llength $notes]
}

add "buy milk" works. add "" stops with the message. error MESSAGE gives an error with the code NONE. throw CODE MESSAGE and return -code error -errorcode CODE set a code.

Stop an error with try

try runs a body and matches the result. trap matches the start of the error code, on error matches each error, and on ok matches a result. finally runs at the end in each case.

catch is the older form. catch {add ""} msg gives 1 for an error and puts the message in msg. The variable errorInfo has the message and the stack of the last error. Run set errorInfo to see the stack, and lindex [split $errorInfo \n] 0 to get its first line.

A catch that hides each error

catch {...} with no check of its result hides each error: a typo, a missing variable, and a full disk look the same. proc save {} { catch {add ""}; return ok } and save give ok for a failure.

Reading code an agent wrote

Ask an agent

Make add give an error with the code JOT EMPTY for empty text. In the caller, use try with trap {JOT EMPTY}, and let each other error go up.

Try this

The state of the shell at the start of this lesson
set notes {}