1
votes

Is is possible to specify user defined command on error in tcl script? I want to cleanup the memory on if any error comes. I know that last error is saved in errorInfo variable.

3

3 Answers

4
votes

It's not quite clear what really do you want.

You can trap any error using the catch command. If you need it to work on the top level, you can evaluate the rest of your script under catch, like in

catch {
  source ./the_rest_of_the_code.tcl
} err

For asynchronous programs (those using event loop, Tk included) it's not that easy as unexpected errors can be raised in callbacks. To deal with those look at the bgerror command.

3
votes

The other alternative is to use an execution trace in leavestep mode, which lets you test whether each command executed failed and determine what to do if it occurs. (This is a lot like what you can do with certain types of aspects in AOP.)

proc doIt {} {
    namespace eval :: {
        # Your real code goes in here
    }
}
trace add execution doIt leavestep {::apply {{cmd cmdArgs code result op} {
    if {$code == 1} {#0 == ok, 1 == error
        puts "ERROR >>$result<< from $cmdArgs"
    }
}}}
doIt

It's pretty slow though.

1
votes

You can also define a bgerror procedure and call your code as a background task:

proc bgerror { msg } {
  puts "bgerror:$msg"
  # Cleanup code here
}

proc troubleCode { } { 
  adjsad s ahda 
}

after 1 troubleCode