error-handling - TCL中的错误处理

标签 error-handling tcl

我有以下步骤:

proc show_information {args} {
set mandatory_args {
        -tftp_server
        -device ANY
        -interface ANY

}
set optional_args {
        -vlan ANY

}

parse_dashed_args -args $args -optional_args $optional_args -mandatory_args $mandatory_args

log -info "Logged in device is: $device"
log -info "Executing proc to get all data"
set commands {
              "show mpls ldp neighbor"
              "show mpls discovery vpn"
              "show mpls interface"
              "show mpls ip binding"
              "show running-config"
              "show policy-map interface $intr vlan $vlan input"
              "show run interface $intr
            }

foreach command $commands {
    set show [$device exec $command]
    ats_log -info $show

  }
 }

我是tcl的新手,并且想知道如果传递错误的参数或错误输出,如何处理错误。
诸如python的尝试*(执行proc),而*(在失败的情况下打印一些msg)除外。

经过一番谷歌搜索后,TCL中使用了“catch”,但无法弄清楚如何使用它。

最佳答案

catch命令运行脚本并捕获其中的任何失败。该命令的结果实际上是一个 bool(boolean) 值,用于描述是否发生错误(实际上是一个结果代码,但是0是成功,1是错误;还有其他一些,但是您通常不会遇到它们)。您还可以给变量放置“结果”,这是成功时的正常结果,失败时的错误消息。

set code [catch {
    DoSomethingThat mightFail here
} result]

if {$code == 0} {
    puts "Result was $result"
} elseif {$code == 1} {
    puts "Error happened with message: $result"
} else {
    # Consult the manual for the other cases if you care
    puts "Code: $code\nResult:$result"
}

在许多简单的情况下,您可以将其缩短为:
if {[catch {
    DoSomethingThat mightFail here
} result]} {
    # Handle the error
} else {
    # Use the result
}

Tcl 8.6添加了新命令来处理错误。 try命令与您使用Python时更像:
try {
    DoSomethingThat mightFail here
} on error {msg} {
    # Handle the error
}

它还支持finallytrap子句,以分别确保操作和更复杂的错误处理。例如(用catch编写的代码很烦人):
try {
    DoSomethingThat mightFail here
} trap POSIX {msg} {
    # Handle an error from the operating system
}

关于error-handling - TCL中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198502/

相关文章:

python - S3 : Invalid bucket name - Bucket name must match the regex

asp.net - 从 SQLException 错误输出异常

error-handling - 在所有 PHP 错误上显示自定义错误页面并将它们通过电子邮件发送给管理员

tcl 字符串替换

tcl - Tcl 中的变量范围

Linux:如何找出我的库的哪个(子)依赖项需要特定的库?

regex - 非贪婪正则表达式根据原子在正则表达式中的位置表现贪婪

unit-testing - 如何测试 Haskell 中的错误?

tcl - 如何在tcl中将变量参数从一个函数传递给另一个函数

java - 在 Spring Boot 中,如何在显示 error.html 之前捕获错误并对其进行处理?