What is the difference between reverse code error and error

Actually the difference between raising exceptions in TCL with return -code error ...and error ...? When could it be used instead of another?

+5
source share
1 answer

The command errorcreates an error at the current point; this is great for cases when you throw a problem due to the internal state of the procedure. The command return -code errormakes the procedure by which it is placed, creates an error (as if the procedure were error); this is great for the case when there is a problem with the arguments passed to the procedure (i.e., the caller did not do something wrong). The difference does occur when you look at the stack trace.

Here is an example (far-fetched!):

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"
+5
source

All Articles