Error handling TCL中的错误处理
我有以下程序:Error handling TCL中的错误处理,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 $mand
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的新手,想知道如果我们传递了错误的参数或它出错了,我们如何处理错误。
类似于TCL中的python try*(执行过程)和except*(在失败时打印一些消息)
在谷歌搜索之后,“catch”是TCL中使用的,但我不知道如何使用它。catch命令运行脚本并捕获其中的任何故障。该命令的结果实际上是一个描述是否发生错误的布尔值(它实际上是一个结果代码,但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
}
它还支持finally
和trap
子句,分别用于保证操作和更复杂的错误处理。例如(用catch
编写的东西很烦人):
catch
命令运行脚本并捕获其中的任何故障。该命令的结果实际上是一个描述是否发生错误的布尔值(它实际上是一个结果代码,但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
}
它还支持finally
和trap
子句,分别用于保证操作和更复杂的错误处理。例如(用catch
编写的东西很烦人):
谢谢多纳尔(如果错误,请更正):尝试{show_information{some arguments}}{print“check your arguments”}
尝试{show_information{some arguments}}}}关于错误{msg}{处理错误放置“error$msg”}
我认为最好使用error
来处理错误。或者return
有其他参数<代码>返回-代码错误“我的错误”谢谢多纳尔(如果错误请更正):尝试{show_information{some arguments}}{print“check your arguments”}尝试{show_information{some arguments}}关于错误{msg}{{处理错误放置“error$msg”}
我认为最好使用错误
来纠正错误。或者return
有其他参数<代码>返回-代码错误“我的错误”