Trapping errors in Tcl - the safety net that catch provides
Archive - Originally posted on "The Horse's Mouth" - 2012-01-06 17:24:26 - Graham EllisWhat could possibly go wrong when you open a file in a program? Lots of things, actually.
* You could try to open a file in directory you cannot access
* You could try to read from a file that does not exist
* You could try to read from something that's not a plain file - e.g. a directory
* You could be trying to read from a file over which you don't have read access
And I'm sure this list is incomplete ...
And if you're writing a program that should be robust, you need to consider all of the above - including that comment "this list is incomplete".
Tests in your program to check that things will work are often a good idea. But they will only test the circumstances that you have come up with - in other words, they are not "fail safe". In some languages, you can check the return status from your file open command and see if it worked - that's a better solution but, alas, in some circumstances / languages such as Tcl your open command won't even return to you to tidy up if it fails, and you need something else. And that's where you need to use exceptions - keywords like try are usually used.
In Tcl - which I have been teaching this week - there's a catch command, and this allows you to wrap a command that may fail, getting back a true value if that failure occurs, and (optionally) a variable containing the error message so that you can report it if you wish. Here's an example:
if {[catch {set fh [open $day r]} excuse]} {
puts "Failed to open - $excuse"
continue }
Full example [here] from our Learning to program in Tcl course.