如果您只是想尝试 - 除非不处理异常,您如何在Python中执行此操作?
以下是正确的方法吗?
try:
shutil.rmtree(path)
except:
pass
#1楼
try:
doSomething()
except Exception:
pass
else:
stuffDoneIf()
TryClauseSucceeds()
FYI else子句可以在所有异常之后执行,并且只有在try中的代码不会导致异常时才会运行。
#2楼
首先,我从这个帖子中引用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
#3楼
为了完整性:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
...来自python教程 。
另请注意,您可以像这样捕获异常:
>>> try:
... this_fails()
... except ZeroDivisionError as detail:
... print 'Handling run-time error:', detail
#4楼
如何正确忽略异常?
有几种方法可以做到这一点。
但是,示例的选择有一个简单的解决方案,不包括一般情况。
具体到示例:
代替
try:
shutil.rmtree(path)
except:
pass
做这个:
shutil.rmtree(path, ignore_errors=True)
这是shutil.rmtree
特有的参数。 您可以通过执行以下操作来查看有关它的帮助,您将看到它也可以允许错误功能。
>>> import shutil
>>> help(shutil.rmtree)
由于这只涵盖了示例的狭义情况,因此如果不存在这些关键字参数,我将进一步演示如何处理此问题。
一般的做法
由于以上仅涵盖示例的狭义情况,因此,如果不存在这些关键字参数,我将进一步演示如何处理此问题。
Python 3.4中的新功能:
您可以导入suppress
上下文管理器:
from contextlib import suppress
但只能压制最具体的异常:
with suppress(FileNotFoundError):
shutil.rmtree(path)
您将默默地忽略FileNotFoundError
:
>>> with suppress(FileNotFoundError):
... shutil.rmtree('bajkjbkdlsjfljsf')
...
>>>
来自文档 :
与完全抑制异常的任何其他机制一样,此上下文管理器应仅用于涵盖非常具体的错误,其中已知正在继续执行程序是正确的。
请注意, suppress
和FileNotFoundError
仅在Python 3中可用。
如果您希望代码也在Python 2中工作,请参阅下一节:
Python 2&3:
如果你只是想尝试/除了不处理异常,你如何在Python中做到这一点?
以下是正确的方法吗?
try : shutil.rmtree ( path ) except : pass
对于Python 2兼容代码, pass
是获得无操作语句的正确方法。 但是当你执行以下操作时except:
,这与except BaseException:
的操作相同except BaseException:
包括GeneratorExit
, KeyboardInterrupt
和SystemExit
,一般情况下,您不希望捕获这些内容。
实际上,您应该尽可能详细地命名异常。
这是Python(2) 异常层次结构的一部分,正如您所看到的,如果您捕获更多常规异常,则可以隐藏您不期望的问题:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
... and so on
你可能想在这里捕获一个OSError,也许你不关心的例外是没有目录。
我们可以从errno
库中获取该特定的错误号,如果我们没有,则重新加载:
import errno
try:
shutil.rmtree(path)
except OSError as error:
if error.errno == errno.ENOENT: # no such file or directory
pass
else: # we had an OSError we didn't expect, so reraise it
raise
注意,裸引发会引发原始异常,这可能是您在这种情况下所需要的。 写得更简洁,因为我们不需要在异常处理中明确pass
代码:
try:
shutil.rmtree(path)
except OSError as error:
if error.errno != errno.ENOENT: # no such file or directory
raise
#5楼
在Python中,我们处理类似于其他语言的异常,但区别在于一些语法差异,例如,
try:
#Your code in which exception can occur
except <here we can put in a particular exception name>:
# We can call that exception here also, like ZeroDivisionError()
# now your code
# We can put in a finally block also
finally:
# Your code...
#6楼
只需提出相关的异常,就像这样:
try:
raise NameError('Joan')
except NameError:
print 'An exception just raised again by Joan!'
raise
就如此容易。 :)
有关更多详细信息,请阅读此文档: https : //docs.python.org/3.6/tutorial/errors.html
#7楼
我需要忽略多个命令中的错误,而fuckit就是这样做的
import fuckit
@fuckit
def helper():
print('before')
1/0
print('after1')
1/0
print('after2')
helper()
#8楼
try:
doSomething()
except:
pass
要么
try:
doSomething()
except Exception:
pass
不同的是,第一个也会捕获KeyboardInterrupt
, SystemExit
和类似的东西,它们直接派生自exceptions.BaseException
,而不是exceptions.Exception
。
有关详情,请参阅文档
- try语句 - http://docs.python.org/reference/compound_stmts.html#try
- 例外 - http://docs.python.org/library/exceptions
#9楼
当你只想尝试catch而不处理异常时,你如何在Python中做到这一点?
这取决于“处理”的含义。
如果您想在不采取任何措施的情况下捕获它,您发布的代码将起作用。
如果你的意思是你想对异常采取行动而不停止异常上升,那么你想要这样的东西:
try:
do_something()
except:
handle_exception()
raise #re-raise the exact same exception that was thrown
#10楼
通常认为只捕获您感兴趣的错误的最佳做法。在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
而不是bare except:
语句。 再次,为什么?
不指定异常会捕获每个异常,包括SystemExit
异常,例如sys.exit()
使用的异常:
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
将此与以下内容进行比较,正确退出:
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
如果你想编写更好的行为代码, OSError
异常可以代表各种错误,但在上面的例子中我们只想忽略Errno 2
,所以我们可以更具体:
try:
shutil.rmtree(path)
except OSError, e:
if e.errno == 2:
# suppress "No such file or directory" error
pass
else:
# reraise the exception, as it's an unexpected error
raise
你也可以import errno
并将if
更改为if e.errno == errno.ENOENT:
#11楼
当你只想尝试catch而不处理异常时,你如何在Python中做到这一点?
这将帮助您打印异常是什么:(即尝试catch而不处理异常并打印异常。)
import sys
try:
doSomething()
except:
print "Unexpected error:", sys.exc_info()[0]