Tcl - Error Handling


Advertisements


Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below.

Error syntax

error message info code

In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode.

Catch Syntax

catch script resultVarName

In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error.

An example for simple error handling is shown below −

Live Demo
#!/usr/bin/tclsh

proc Div {a b} {
   if {$b == 0} {
      error "Error generated by error" "Info String for error" 401
   } else {
      return [expr $a/$b]
   }
}

if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
   puts "ErrorMsg: $errmsg"
   puts "ErrorCode: $errorCode"
   puts "ErrorInfo:\n$errorInfo\n"
}

if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
   puts "ErrorMsg: $errmsg"
   puts "ErrorCode: $errorCode"
   puts "ErrorInfo:\n$errorInfo\n"
}

When the above code is executed, it produces the following result −

ErrorMsg: Error generated by error
ErrorCode: 401
ErrorInfo:
Info String for error
   (procedure "Div" line 1)
   invoked from within
"Div 10 0"

Result = 5

As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below −

Live Demo
#!/usr/bin/tclsh

catch {set file [open myNonexistingfile.txt]} result
puts "ErrorMsg: $result"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"

When the above code is executed, it produces the following result −

ErrorMsg: couldn't open "myNonexistingfile.txt": no such file or directory
ErrorCode: POSIX ENOENT {no such file or directory}
ErrorInfo:
couldn't open "myNonexistingfile.txt": no such file or directory
   while executing
"open myNonexistingfile.txt"


Advertisements