Exception handling in Tcl
Archive - Originally posted on "The Horse's Mouth" - 2013-11-14 13:23:57 - Graham EllisExceptions are a wonderful fail safe way of trapping errors in most modern programming languages. Although the natural way for a newcomer to programming to handle unusual situations is to test for each possible situation, that becomes a guessing game trying to work out everything that may happen, and things can get overlooked. But with exceptions, you're saying "if this doesn't work out for any reason, please jump to the following recovery code."
You would think with a language such as Tcl that's approaching 30 years old, exceptions might be missing - but you're only half right in that thought. For Tcl uses a catch command to run another command (or block of commands) under a subsidiary control, returning a true value if something hasn't functioned in the normal way. You can specify a variable to grab the system message telling you what didn't work as well. So
if {[catch {set many [expr $value * 100]} excuse]} {
will return a false value if the calculation works, and a true value (together with an explanation of the reason in excuse it it fails. Full example [here].
With an exception caught in Tcl in that way, you can continue the program running rather than have it exit with an error message - and that's a big benefit in Tcl, where syntax checking only happens as the code runs, so a lot of time may be lost by a program that crashes out towards the end of a long run.