当你只想做一个 try-except 而不处理异常时,你如何在 Python 中做到这一点?
以下是正确的方法吗?
try:
shutil.rmtree(path)
except:
pass
原文由 Joan Venge 发布,翻译遵循 CC BY-SA 4.0 许可协议
当你只想做一个 try-except 而不处理异常时,你如何在 Python 中做到这一点?
以下是正确的方法吗?
try:
shutil.rmtree(path)
except:
pass
原文由 Joan Venge 发布,翻译遵循 CC BY-SA 4.0 许可协议
通常认为最好的做法是只捕获您感兴趣的错误。在 shutil.rmtree
的情况下,它可能是 OSError
:
>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
如果你想默默地忽略那个错误,你会这样做:
try:
shutil.rmtree(path)
except OSError:
pass
为什么?假设您(以某种方式)不小心将整数而不是字符串传递给函数,例如:
shutil.rmtree(2)
它会给出错误 “TypeError: coercing to Unicode: need string or buffer, int found” ——你可能不想忽略它,这可能很难调试。
如果您 绝对 想忽略所有错误,请捕获 Exception
而不是裸露的 except:
语句。再一次,为什么?
不指定异常会捕获 所有 异常,包括 SystemExit
异常,例如 sys.exit()
使用:
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
将此与以下正确退出的内容进行比较:
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
如果您想编写性能更好的代码, OSError
异常可以表示各种错误,但在上面的示例中我们只想忽略 Errno 2
,因此我们可以更具体:
import errno
try:
shutil.rmtree(path)
except OSError as e:
if e.errno != errno.ENOENT:
# ignore "No such file or directory", but re-raise other errors
raise
原文由 dbr 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
或者
The difference is that the second one will also catch
KeyboardInterrupt
,SystemExit
and stuff like that, which are derived directly fromBaseException
, notException
。有关详细信息,请参阅文档:
try
声明但是,捕获每个错误通常是不好的做法 - 请参阅 为什么“除了:通过”是一种不好的编程做法?