backstreetrover
backstreetrover

Reputation: 323

Why can I not catch undefined variable Error

Why does the below code not catch error:

rename list _native_list
proc list {args} {
  uplevel 1 {
    if { [catch {_native_list $args} val] } {
      puts "list $args :: FAILED $val"
    } else {
      return $val
    }
  }
}

When trying to execute the newly defined list command, this is what I get:

% list hi $h
can't read "h": no such variable

Why did it not trap the error?

Upvotes: 0

Views: 540

Answers (2)

mrcalvin
mrcalvin

Reputation: 3434

A first step, rather than DIY, is to use a static program analyzer, e.g., nagelfar. It supports some detection of references to non-existing and uninitialized (a.k.a. undefined in Tcl lingo) variables.

For a file t.tcl with content:

namespace eval ::ns1 {
    list $i
}

proc foo {h} {
    list $h
}

nagelfar yields true positives:

% ./tclkit nagelfar132.kit t.tcl
Checking file t.tcl
Line   2: E Unknown variable "i"
Line   6: E Unknown variable "h"

But, beware, Tcl does not fully lean itself towards static analyses of this sort, nagelfar will yield false positives in case of computed variable names, computed formal arguments lists to procs etc.

Dynamic approaches by partially (re-)evaluating a script to record such variable references will likely break even scripts of low complexity to a point making the results worthless, if any at all.

Upvotes: 2

Chris Heithoff
Chris Heithoff

Reputation: 1863

The proc isn't even getting called. The error is happening when the $h argument in the argument is evaluated. $h is undefined, so you can't send that as an argument to the proc.

Upvotes: 3

Related Questions