【发布时间】:2011-02-17 01:35:05
【问题描述】:
我想知道在 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
但我想知道是否有更短的方法。
【问题讨论】:
-
使用
except:是个坏主意。最好使用except SomeSpecificError:并处理您知道如何处理的特定异常。except:会捕获各种你不注意的异常,包括内存不足或用户按 ctrl-C。 -
except Exception一般推荐
标签: python error-handling try-catch