Error handling procedure

In this section, we will build an error handling procedure to expand on the catch construct example presented earlier. This recipe will accept a filename and a program name. If the file exists and can be opened for reading it will attempt to open the file within the program passed. If the file can be opened but the program fails for any other reason we will display an error message of our own creation.

Getting ready

To complete the following example we will need to create a Tcl script file in your working directory. Open the text editor of your choice and follow the given instructions.

How to do it…

Using the editor of your choice, create a text file named error_handling.tcl that contains the following commands:

#Check that two arguments were passed
if { $argc == 2 } {
	#Define variables for the filename, program
	set fname [lindex $argv 0]
	set progname [lindex $argv 1]
	#Check that the file exists for reading
	set retval [file readable $fname]
	#If the file exists for reading we will open it with the desired 
program
	if {$retval !=1} {
		puts "The file $fname is not available"
	} else {
		# Attempt to open the file
		set status 0
		if {[catch {exec $progname $fname &} results options]} {
			# Obtain the dictionary values for the error
			set details [dict get $options -errorcode]
			set status [lindex $details 2]
			# Display the error message
			puts "$progname: $status"
		}
	}
} else {
	puts "This program requires two arguments - Filename and 
ProgramName"
}

Now call the script with the following command line replacing notepad if that is not a valid program for your operating system:


% tclsh85 error_handling.tcl catch.tcl notepad
%

How it works…

Our error handling procedure has evaluated the passed argument. It was provided a valid argument and located a readable file. Based on this, it has proceeded to call the executable file and load the desired file.

Call the script a second time with the following command line:


% tclsh85 error_handling.tcl nofile notepad
The file nofile is not available
%

As you can see, notepad (or the text editor of your choice) was not launched, as a readable file did not exist.

Now call the script with the following command line:


% tclsh85 error_handling.tcl catch.tcl noprogram
noprogram: no such file or directory

The catch construct allowed us to trap the error and present the enduser with an error message of our choice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.250