当你只想做一个try-except而不处理异常时,你在Python中如何做呢?
下面的方法是正确的吗?
try:
shutil.rmtree(path)
except:
pass
当你只想做一个try-except而不处理异常时,你在Python中如何做呢?
下面的方法是正确的吗?
try:
shutil.rmtree(path)
except:
pass
当前回答
通常认为最佳实践是只捕获您感兴趣的错误。在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
其他回答
通常认为最佳实践是只捕获您感兴趣的错误。在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
当你只想做一个try catch而不处理异常时, 用Python怎么做?
这将帮助你打印异常是什么:(即尝试catch而不处理异常并打印异常。)
import sys
try:
doSomething()
except:
print "Unexpected error:", sys.exc_info()[0]
我通常会这样做:
try:
doSomething()
except:
_ = ""
try:
doSomething()
except Exception:
pass
else:
stuffDoneIf()
TryClauseSucceeds()
供您参考,else子句可以放在所有异常之后,只有在try中的代码没有导致异常时才会运行。
首先我引用Jack o'Connor的回答。引用的线程已经关闭,所以我在这里写道:
“在Python 3.4中有一种新的方法可以做到这一点:
from contextlib import suppress
with suppress(Exception):
# your code
下面是添加它的提交:http://hg.python.org/cpython/rev/406b47c64480
这里是作者Raymond Hettinger,他谈到了这个和其他各种Python热点:https://youtu.be/OSGv2VnC0go?t=43m23s
我对它的补充是Python 2.7的等效:
from contextlib import contextmanager
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
然后像在Python 3.4中那样使用它:
with ignored(Exception):
# your code