这是一个测试用例。
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
print targ
当我按ctrl + c -
时,我的输出如下NameError: name 'targ' is not defined
我的意图是输出为“已取消”。当我在raw_input期间尝试捕获KeyboardInterrupt时,有什么想法会发生这种情况吗?
谢谢!
答案 0 :(得分:4)
在上面的代码中,当引发异常时,没有定义targ。只有在未引发异常时才应打印。
try:
targ = raw_input("Please enter target: ")
print targ
except KeyboardInterrupt:
print "Cancelled"
答案 1 :(得分:2)
发生错误是因为如果引发KeyboardInterrupt
,变量targ
永远不会被初始化。
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
Please enter target:
Cancelled
>>> targ
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
targ
NameError: name 'targ' is not defined
何时,它不会发生,
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
Please enter target: abc
>>> targ
'abc'
如果未引发异常,您可以将代码更改为打印targ
,方法是在try
语句中打印,请参阅以下演示。
try:
targ = raw_input("Please enter target: ")
print targ
except KeyboardInterrupt:
print "Cancelled"
Please enter target: abc
abc
try:
targ = raw_input("Please enter target: ")
print targ
except KeyboardInterrupt:
print "Cancelled"
Please enter target:
Cancelled