trap

The trap proc which essentially works like 'if catch then body'. ufko.org

# Procedure: trap
# Essentially works like 'if catch then body'.
# Trap stores the latest error in the 'traperror' auto variable
# in the caller's scope.
# Returns 1 on error 0 on success
# Example usages:
# trap {lassing} -> ignore the error and continue
# trap {lassign} {puts $traperror}
# trap {lassign} {puts "Recovering ..."; lassign {b} a}
# if {[trap {lassign}]} { puts $traperror; do this } else {do that}
proc trap {cmd {body ""}} {
  set level [expr {[info level] - 1}]
  set caller [lindex [info level $level] 0]
  set code [catch {uplevel 1 $cmd} err]

  if {$code} {
    if {$level == 0} {
      set err "Trap in level 0 in proc: ${caller} <- '$cmd': $err"
    } else {
      set err "Trap in proc: ${caller} <- '$cmd': $err"
    }

    uplevel 1 [list set traperror $err]
    if {$body ne ""} {
      uplevel 1 $body
    }
  }
  return $code
}

MJ - what does this add to the builtin try command?

ufko.org - Mark, thanks for your input, but trap is designed for simplicity and minimalism. It adds nothing, on the contrary, it removes the unnecessary :D ... try is fine, but trap is more compact, especially for quick inline error handling. Not everyone wants extra structures or dependencies. Use what fits your needs.


TWu - 2025-03-11 15:42:15

try was buid-in for TCL version 8.6 and a tcllib package exists for TCL version 8.5.
Maybe this is an additional way to get this functionality for older versions or without the tcllib package.

ufko.org Thomas, I'm using 9.0 ... Regarding tcllib, I’d rather call an external C program or Go program that returns exactly what I need.