关于TCL中的错误清除机制

时间:2016-02-01 13:27:26

标签: tcl

如果函数本身发生错误,则调用适当函数的机制。

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 {} {
}

尝试exit代替error,但我无法在TclX的信号函数中找到退出,

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

错误就像是,你不能使用Exit作为参数来发信号。

我知道的一件事是,我可以在函数调用时捕获该错误。等,

set retval [catch {abc}]

但是我可以在函数内部有一些机制,如代码的第一部分的注释中给出的那种中断处理程序。

感谢。

1 个答案:

答案 0 :(得分:2)

如果您使用的是Tcl 8.6,最简单的机制是:

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

否则(8.5或之前),您可以在未使用的局部变量上使用未设置的跟踪来触发清理代码:

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
    }
}

如果您使用的是8.6,则应使用try … finally …,因为您可以更清晰地访问abc的局部变量;未设置的痕迹可以在相对困难的时候运行。