Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch "Tcl Interpreter Error"

Tags:

tcl

Is there any way to catch the global "Tcl Interpreter Error"? For example I would like to automatically store in some file the message that follows.

like image 307
ilya1725 Avatar asked Mar 30 '12 21:03

ilya1725


2 Answers

The core command for trapping any kind of error thrown by Tcl is catch. It takes at least one argument, a script to evaluate, and returns the result code from evaluating that script. The result code is 1 when an error occurs, 0 when there was no error, and a bunch of other things in other cases (indicating other types of usually-non-error exception). The catch also takes an optional argument that names a variable into which to write the result of evaluating the script or the error message. The global variable errorInfo will contain the stack trace in the case of an error (or from 8.5 onwards you can get the interpreter state dictionary with a further variable name passed to catch).

To trap an error in some script “foo.tcl”, you would use code like this:

if {[catch {source foo.tcl} msg]} {
    puts "I got an error: $msg"
    puts "The stack trace was this:\n$errorInfo"
}

It's up to you to work out how to write that out to a file if you want. (I use this technique with an outer script that implements a carefully tested error trap and which loads an inner script that does the real work. I find it works well. Or you can call procedures in that “caught” script. Up to you really; Tcl should make all errors trappable, and there are very few conditions which slip through.)


The other route that errors can be reported is via bgerror, which is called to handle errors that occur during event processing. It's a procedure you can write your own version of; it will be given a single argument when called that is the error message, and will have the global errorInfo set correctly when called:

proc bgerror {msg} {
    global errorInfo
    puts "I got an error in an event: $msg"
    puts "The stack trace was this:\n$errorInfo"
}

If there is no implementation of bgerror defined, the stack trace is just written to the stderr channel. If you're using the Tk package, an implementation of bgerror is provided which pops up a dialog box describing the problem.

like image 139
Donal Fellows Avatar answered Sep 30 '22 07:09

Donal Fellows


Try the bgerror or interp bgerror commands.

Read the bgerror documentation, it has a simple example.

like image 25
schlenk Avatar answered Sep 30 '22 06:09

schlenk