浅谈TCL中的错误清除机制

On Error Cleanup Mechanism in 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}]

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

谢谢。

如果您使用的是 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 的局部变量;未设置的痕迹可以 运行 在相对困难的时候。