Reputation: 3174
Im trying to learn Expect scripting to run backend process, is there a way to raise and catch an error exception from this language?
Ex. Python
try:
raise Exception("test")
except Exception, e:
print e
What's the equivalent in expect?
#!/usr/bin/expect
package require Expect
# raise and catch exception
Upvotes: 0
Views: 714
Reputation: 137767
If you're using Tcl 8.6 (which the Expect package will load into nicely), the most literal translation of that Python code is:
try {
throw Exception "test"
} trap Exception e {
puts $e
}
Now, the try
and throw
commands were added in 8.6 to make this sort of thing easier. Prior to that (all the way from far further back than I can search conveniently) you would instead do something like this:
if {[catch {
error "test"
} e] == 1} {
puts $e
}
Which is easy enough in this case, but rather more error-prone once things get more complex.
Upvotes: 1
Reputation: 247142
The A literal translation of your python example is
set status [catch {error "test"} e]
if {$status} {
puts $e
}
This is Tcl 8.5
Upvotes: 1
Reputation: 40773
In TCL, you can use catch
to catch an exception:
if {[catch { package require Expect } errmsg]} {
puts "Import failed with message: $errmsg"
} else {
puts "Import succeeded"
}
To throw an exception, use the return -code error
command. For example:
proc double {x} {
if {![string is integer $x]} {
return -code error "double expects an int, not '$x'"
}
return [expr {$x * 2}]
}
set x 5
puts "x = $x"
puts "2x = [double $x]"
set x "Hello"
puts "x = $x"
if {[catch {puts "2x = [double $x]"} errmsg]} {
puts "Error: $errmsg"
}
Output:
x = 5
2x = 10
x = Hello
Error: double expects an int, not 'Hello'
Upvotes: 1