Version 5 of error

Updated 2002-01-11 22:48:13

RS In C, errors are something you loathe and try to avoid. In Tcl, they're like "little friends" - helpful (explaining the problem), not messing up everything (as a Segmentation Fault/Bus Error/Divide by Zero would do). For instance,

 set fp [open]

leads to the error

 couldn't open "": no such file or directory

which tells it pretty well, and does not terminate the application (if it has an event loop or is interactive). In C, you would have received a NULL pointer, and without checking that, Segmentation Fault would be right around the corner. So in C, you have to add checks for everything that might go wrong; in Tcl, you only need to treat errors if you can express it better than Tcl already does.

And you can also play with errors: to fully break out of a multiply nested loop, put a catch outside and a throw within:

 catch {
    ...# deep nesting ...

There is no throw command in Tcl, so it is handled by unknown, which tries to load it from auto_index, and if that fails too, an error is raised - which in turn is caught by the catch. Pretty natural, no? And still somehow Zen buddhistic, if you deliberately use a non-existing command, and it does just the right thing... (Kevin Kenny introduced this trick in Tricky catch).

In some cases, stack traces look better (one less layer) if you replace

 error "Something went wrong"


 return -code error "Something went wrong"

Tcl syntax help - Arts and crafts of Tcl-Tk programming - Category Command