The -code option is rarely used. It is provided so that procedures that implement new control structures can reflect exceptional conditions back to their callers.
Two additional options, -errorinfo and -errorcode, may be used to provide additional information during error returns. These options are ignored unless code is error.
The -errorinfo option specifies an initial stack trace for the errorInfo variable; if it is not specified then the stack trace left in errorInfo will include the call to the procedure and higher levels on the stack but it will not include any information about the context of the error within the procedure. Typically the info value is supplied from the value left in errorInfo after a catch command trapped an error within the procedure.
If the -errorcode option is specified then code provides a value for the errorCode variable. If the option is not specified then errorCode will default to NONE.
proc printOneLine {} {
puts "line 1" ;# This line will be printed.
return
puts "line 2" ;# This line will not be printed.
}
Next, an example of using return to set the value returned by the procedure.
proc returnX {} {return X}
puts [returnX] ;# prints "X"
Next, a more complete example, using return -code error to report invalid arguments.
proc factorial {n} {
if {![string is integer $n] || ($n < 0)} {
return -code error \
"expected non-negative integer,\
but got \"$n\""
}
if {$n < 2} {
return 1
}
set m [expr {$n - 1}]
set code [catch {factorial $m} factor]
if {$code != 0} {
return -code $code $factor
}
set product [expr {$n * $factor}]
if {$product < 0} {
return -code error \
"overflow computing factorial of $n"
}
return $product
}
Next, a procedure replacement for break.
proc myBreak {} {
return -code break
}
Copyright © 1993 The Regents of the University of California. Copyright © 1994-1996 Sun Microsystems, Inc. Copyright © 1995-1997 Roger E. Critchlow Jr.