Main Content

Exceptions - Tcl style

Archive - Originally posted on "The Horse's Mouth" - 2011-05-12 07:27:00 - Graham Ellis

Checking for all possible errors isn't a "failsafe" way of coding. If you try and check for absolutely any error, you're still very likely to miss one or two possibilities, and it's fare better to add a block to your code to say (in essence) "if anything at all goes wrong, go here...". And that's commonly known as throwing and catching exceptions.

Tcl has a catch command:
  catch {code block} varname
in which you can wrap a piece of code from which you want to catch exceptions. The result of running the block - either its return value or error message - will be saved into the named variable. Catch also return a true / false boolean so that you know whether or not an exception was thrown. So - put your catch into an if block ... and add exception handling code in the optional block. There's a full example [here] from the Tcl course I was teaching yesterday.

Tcl also supports an unknown command, which is run if you ask for a command that's not defined to be run. That's a further type of exception catching - also illustrated in the example that I've linked to above.