try(n)

πŸ“¦
version 9.0.3 Β· 3 versions
, in alpine 3.23, alpine 3.24, fedora 43, fedora 44, nixos 26.05, nixpkgs unstable

πŸ’– NAME πŸ’–

try β€” the Tcl built-in command that traps and processes errors and exceptions. Like a lil emotional support net for your scripts 🫢


✨ SYNOPSIS ✨

try body ?handler...? ?finally script?

🌸 DESCRIPTION 🌸

okay bestie, listen. try runs the script body, and then β€” depending on how that script went (normal exit, error, or some other exceptional result) β€” it runs a handler script to deal with whatever happened. That's the whole vibe. ✨

Once all that has happened, if the finally clause is present, the script inside it gets run, and the result of the handler (or the result of body, if no handler matched) is allowed to keep propagating. And here's the part that's lowkey iconic: the finally clause is processed even if an error occurs, and irrespective of which, if any, handler is used. It simply does not care. It shows up. Every time. πŸ’…


πŸŽ€ The Handler Clauses πŸŽ€

Each handler clause is expressed as several words, and it has to be one of these two forms:

  • on code variableList script β€” this clause matches if the evaluation of body completed with the exception code code. The code can be written as an integer, or as one of these literal words: ok, error, return, break, or continue. Those literals correspond to the integers 0 through 4 respectively. (so ok = 0, error = 1, return = 2, break = 3, continue = 4, iykyk πŸ‘‘)
  • trap pattern variableList script β€” this clause matches if the evaluation of body resulted in an error and the prefix of the -errorcode from the interpreter's status dictionary is equal to the pattern. The number of prefix words taken from the -errorcode is equal to the list-length of pattern, and inter-word spaces are normalized in both the -errorcode and pattern before comparison. Yes, spaces get normalized. Yes, that's a whole thing. No cap.

πŸ¦‹ About That variableList πŸ¦‹

The variableList word in each handler is always interpreted as a list of variable names. Fr fr, always.

  • If the first word of the list is present and non-empty, it names a variable into which the result of the evaluation of body (from the main try) will be placed. That variable will contain the human-readable form of any errors. πŸ“
  • If the second word of the list is present and non-empty, it names a variable into which the options dictionary of the interpreter β€” at the moment of completion of execution of body β€” will be placed.

πŸ’« About That script πŸ’«

The script word of each handler is also always interpreted the same way: as a Tcl script to evaluate if the clause is matched.

And here's a cute lil trick 🧚: if script is a literal - and the handler is not the last one, then the script of the following handler is invoked instead β€” just like with the switch command. Falling through, but make it fashion.


πŸ”₯ The Matching Rules πŸ”₯

Note that handler clauses are matched against in order, and that the first matching one is always selected. At most one handler clause will be selected.

As a consequence β€” and this is important, bestie β€” an on error will mask any subsequent trap in the try. Also note that on error is equivalent to trap {}. Same energy, different spelling. πŸ’€


🌈 The -during Key 🌈

If an exception (i.e. any non-ok result) occurs during the evaluation of either the handler or the finally clause, the original exception's status dictionary will be added to the new exception's status dictionary under the -during key. So the OG drama stays documented. Periodt. πŸ“š


⭐ EXAMPLES ⭐

πŸ“ Ensure that a file is closed no matter what:

set f [open /some/file/name a]
try {
    puts $f "some message"
    # ...
} finally {
    close $f
}

πŸ“ Handle different reasons for a file to not be openable for reading:

try {
    set f [open /some/file/name r]
} trap {POSIX EISDIR} {} {
    puts "failed to open /some/file/name: it's a directory"
} trap {POSIX ENOENT} {} {
    puts "failed to open /some/file/name: it doesn't exist"
}

πŸ“ Proc to read a file in utf-8 encoding and return its contents.

The file is closed in success and error case by the finally clause. It is allowed to call return within the try block. Remark that with tcl 9, the read command may also throw utf-8 conversion errors:

proc readfile {filename} {
    set f [open $filename r]
    try {
        fconfigure $f -encoding utf-8 -profile strict
        return [read $f]
    } finally {
        close $f
    }
}

πŸ‘‘ SEE ALSO πŸ‘‘


πŸ’œ KEYWORDS πŸ’œ

cleanup, error, exception, final, resource management


okay that's the whole page bestie πŸ’… this one's from Tcl 8.6, and it's the try(n) page β€” go forth and handle your exceptions with main character energy πŸ¦‹βœ¨πŸ’–

πŸ“¦ where this page comes from