Main Content

Tcl - catching an error before your program crashes

Archive - Originally posted on "The Horse's Mouth" - 2009-10-22 06:49:50 - Graham Ellis

There are times when a Tcl command can fail because of the data being passed in to it ... and when it fails, it can do so with a spectacular crash! For example, the glob command which matches files to a pattern (Tcl's ls or dir if you like to think of it that way) can go 'belly up' if there are no files at all that match the pattern:

no files matched glob pattern "*.lua"
   while executing
"glob *.lua"
   invoked from within
"set file [glob *.lua]"
   (file "tcl/falls" line 15)


OOooops!

If you want your Tcl program to continue, even on an error, you should use the catch command and run the command that may fail within a deferred block that's passed in to it ... something like:

catch {glob *.lua} yikes.

It works like this:
• If the command WORKS, the result is put back into the yikes variable, and catch returns a true value, but
• if the command FAILS, an error message is put into the yikes variable, and catch returns a false value.

There's a code example here that illustrates catching (on glob) with testihng the conditionals. And further examples here (failing) and here (caught). There's also a further explanation on the blog here, and a demonstration of how catch can handle a failure to open a file here.

When you are first writing a piece of code - writing what's known as a 'proof of concept' or a 'spike solution', you may not be thinking about error handling too much. But it reallity such code testing / defensive coding against errors is VITAL. So we make certain that we cover catch and loads of associated subjects on our Tcl Programming courses.