2016-02-01 50 views
0

函數本身發生錯誤時調用適當函數的機制。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 

錯誤就好了,你不能用退出作爲參數信號。

我知道的一件事是,我可以在函數調用時捕獲該錯誤。像,

set retval [catch {abc}] 

但是我可以有一些機構內部功能本身的代碼第一部分的評論指定類別的中斷處理程序。

謝謝。

回答

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局部變量吸塵器接入;未設置的痕跡可以在相對困難的時候運行。

+0

你也可以用'catch'和'return'來模擬'try',但是編寫代碼很麻煩。 –

+0

我也有很多代碼之間的多個「如果」,上面的「如果」和低於「如果」,我在問題內提到的。所以我不能使用第一個解決方案把整個代碼放在裏面試試,最後......我會嘗試第二個......這對我來說是新鮮的...... –

+0

請你詳細說明第二個..它在做什麼?如果可能的話 –