import sys
lst = ['b', 0, 2,5]
for entry in lst:
try:
print("****************************")
print("The entry is", entry)
r = 1 / int(entry)
except(ValueError):
print("This is a ValueError.")
except(ZeroDivisionError):
print("This is a ZeroError.")
except:
print("Some other error")
print("The reciprocal of", entry, "is", r)
当程序将输入作为2时,除块外的打印语句将被跳过。但是,如果我在列表中仅给出3个元素,它将正常工作。
这是因为print
语句在for循环之外。因此,它仅打印entry
的最后一次迭代。
检查此:
In [1340]: import sys
...: lst = ['b']
...: for entry in lst:
...: try:
...: print("****************************")
...: print("The entry is", entry)
...: r = 1 / int(entry)
...: except(ValueError):
...: print("This is a ValueError.")
...: except(ZeroDivisionError):
...: print("This is a ZeroError.")
...: except:
...: print("Some other error")
...: print("The reciprocal of", entry, "is", r)
****************************
The entry is b
This is a ValueError.
The reciprocal of b is 0.2