2018-06-07

try and finally

在 comp.lang.tcl 看到這個寫法,所以我寫了一個練習用的程式來學習這件事:
try 是 Tcl 8.6 內建命令,可以在 finally 釋放所使用的資源。

#!/usr/bin/env tclsh
package require http
package require tls

http::register https 443 [list ::tls::socket -ssl3 0 -ssl2 0 -tls1 1]

set tok {}
set url {https://duckduckgo.com/}

try {
    set tok [http::geturl $url -method GET -timeout 3000]
    puts "Status: [::http::ncode $tok]"
    puts "Status Text: [http::status $tok]"
    puts "Headers: [http::meta $tok]"
} on error {em} {
    puts "Error: $em"
} finally {
    # cleanup here
    if {[info exists tok]==1} {
        http::cleanup $tok
    }
}

(更新:拔掉網路線以後測試,我想需要檢查 tok 是否存在)

相關連結:
try ... finally ... (@ Tclers Wiki!)
TIP 329: Try/Catch/Finally syntax

沒有留言: