Main Content

Error handling in Tcl through catch

Archive - Originally posted on "The Horse's Mouth" - 2005-07-02 09:23:42 - Graham Ellis

Tcl is a truly interpretive language - and that means that you can get a syntax error if a user makes an illegal entry ... even in the middle of a program running. For example


puts -nonewline "please enter a number: "
flush stdout
gets stdin value
set doubled [expr $value * 2]
puts "Result is $doubled"
puts "application continues ..."


Will run correctly if you enter a number to the prompt as requested:


earth-wind-and-fire:~/jul05 grahamellis$ wish ifex
please enter a number: 17
Result is 34
application continues ...
earth-wind-and-fire:~/jul05 grahamellis$


but will fail if you enter something that isn't a number:


earth-wind-and-fire:~/jul05 grahamellis$ wish ifex
please enter a number: lots
Error in startup script: syntax error in expression "lots * 2": variable references require preceding $
  while executing
"expr $value * 2"
  invoked from within
"set doubled [expr $value * 2]"
  (file "ifex" line 6)
earth-wind-and-fire:~/jul05 grahamellis$


If you want to make your Tcl code rugged against such errors, embed commands that may cause a problem within catch commands. Tcl's catch command returns a true of false result depending on whether or not the embedded command succeeds, and if it fails it also returns the error message describing the problem in a variable of your choice. Here's the program above, enhanced to catch any errors:


puts -nonewline "please enter a number: "
flush stdout
gets stdin value
if {[catch {set doubled [expr $value * 2]} errmsg]} {
  puts "Failed - $errmsg"
} else {
  puts "Succeeded and result is $doubled"
}
puts "application continues ..."


And let's try running that. Firstly, with correct data:


earth-wind-and-fire:~/jul05 grahamellis$ wish ifcat
please enter a number: 17
Succeeded and result is 34
application continues ...
earth-wind-and-fire:~/jul05 grahamellis$


And now with data that would previously have caused a crash:


earth-wind-and-fire:~/jul05 grahamellis$ wish ifcat
please enter a number: many
Failed - syntax error in expression "many * 2": variable references require preceding $
application continues ...
earth-wind-and-fire:~/jul05 grahamellis$


Complete source code example - [here].

This approach described here could be described as an expection handling system as it tries to perform an operation and traps if a failure occurs, rather than trying to predict the error ahead of time. An alternative (error handling) system could have been used, in which the code check the input text string to make sure that it's numeric before the expr command is run. We have a comparison of exceptions v errors in our solution centre.