What's the difference between return -code error and error
tcl
Solution
The `error` command produces an error right at the current point; it's great for the cases where you're throwing a problem due to a procedure's internal state. The `return -code error` command makes the procedure it is placed in produce an error (as if the procedure was `error`); it's great for the case where there's a problem with the arguments passed to the procedure (i.e., the caller did something wrong). The difference really comes when you look at the stack trace.
Here's a (contrived!) example:
proc getNumberFromFile {filename} {
if {![file readable $filename]} {
return -code error "could not read $filename"
}
set f [open $filename]
set content [read $f]
close $f
if {![regexp -- {-?\d+} $content number]} {
error "no number present in $filename"
}
return $number
}
catch {getNumberFromFile no.such.file}
puts $::errorInfo
#could not read no.such.file
# while executing
#"getNumberFromFile no.such.file"
catch {getNumberFromFile /dev/null}
puts $::errorInfo
#no number present in /dev/null
# while executing
#"error "no number present in $filename""
# (procedure "getNumberFromFile" line 9)
# invoked from within
#"getNumberFromFile /dev/null"
Problem
What is actually the difference between raising an exception in TCL via `return -code error ...`and `error ...`? When would one be used instead of the other?