我想知道在python中,如果try语句成功的话,有没有一种简单的方法来运行代码,而不是try语句本身。else或finally命令就是这样做的吗(我不理解它们的文档)?我知道我可以使用这样的代码:
successful = False
try:
#code that might fail
successful = True
except:
#error handling if code failed
if successful:
#code to run if try was successful that isn't part of try
但我想知道有没有更短的方法。
发布于 2010-05-08 09:25:12
你想else
for i in [0, 1]:
try:
print '10 / %i: ' % i, 10 / i
except:
print 'Uh-Oh'
else:
print 'Yay!'
发布于 2010-05-08 09:24:58
您正在寻找else
关键词:
try:
#code that might fail
except SomeException:
#error handling if code failed
else:
# do this if no exception occured
发布于 2010-05-08 09:26:22
你的try代码块应该是你想要执行的代码,你的except应该杀死这个程序。我需要更好地理解你的对象才能给出更好的答案。
在OO编程中,您希望“告知,不要询问”,因此保留try块中应该发生的所有逻辑,然后在except块中处理错误。
https://stackoverflow.com/questions/2792568
复制相似问题