toxic_boi_8041
toxic_boi_8041

Reputation: 1492

On Error Cleanup Mechanism in TCL

Mechanism to call appropriate function if error occurred in function itself.

proc abc {} {

    ;# Overhere is it possible to get some mechanism that is used to
    ;# check if error occurs calls appropriate function

    if {something} {
        error "" "" 0
    }
    if {something} {
        error "" "" -1
    }
    if {something} {
        error "" "" 255
    }
}

;# Clean up function
proc cleanup {} {
}

Tried exit instead of error, but i was not able to catch that exit inside signal function of TclX like,

set l1 "INT TERM EXIT HUP"
signal trap $l1 cleanup

Error is like, You can't use Exit as argument to signal.

One thing i know is that, i can catch that error at the time of function calling. like,

set retval [catch {abc}]

But can i have some mechanism inside function itself kind of interrupt handler as given in comment of first part of code.

Thanks.

Upvotes: 0

Views: 267

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137767

If you're using Tcl 8.6, the simplest mechanism is this:

proc abc {} {
    try {
        if {something} {
            error "" "" 0
        }
        if {something} {
            error "" "" -1
        }
        if {something} {
            error "" "" 255
        }
    } finally {
        cleanup
    }
}

Otherwise (8.5 or before), you can use an unset trace on an otherwise-unused local variable to fire the cleanup code:

proc abc {} {
    set _otherwise_unused "ignore this value"
    # This uses a hack to make the callback ignore the trace arguments
    trace add variable _otherwise_unused unset "cleanup; #"

    if {something} {
        error "" "" 0
    }
    if {something} {
        error "" "" -1
    }
    if {something} {
        error "" "" 255
    }
}

If you're using 8.6, you should use try … finally … for this as you've got cleaner access to the local variables of abc; unset traces can run at relatively difficult times.

Upvotes: 2

Related Questions