我怎么能写一个尝试/except块捕获所有异常?


当前回答

非常简单的例子,类似于这里发现的:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

如果您试图捕获所有异常,那么将所有代码放在“try:”语句中,而不是“print”执行可能抛出异常的操作。

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

在上面的例子中,你会看到这样的输出顺序:

1)执行可能引发异常的操作。

2) Finally在执行try语句后直接调用,无论是否抛出异常。

3)“抛出异常!”或“一切看起来都很好!”这取决于是否抛出异常。

希望这能有所帮助!

其他回答

try:
    whatever()
except:
    # this will catch any exception or error

值得一提的是,这不是正确的Python编码。这也将捕获您可能不想捕获的许多错误。

要捕获所有可能的异常,请捕获BaseException。它位于Exception层次结构的顶部:

Python 3: https://docs.python.org/3.10/library/exceptions.html#exception-hierarchy

Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy

try:
    something()
except BaseException as error:
    print('An exception occurred: {}'.format(error))

但正如其他人提到的,你通常不需要这个,只有在非常特定的情况下。

我刚刚发现了在Python 2.7中测试if异常名称的小技巧。有时我在代码中处理了特定的异常,所以我需要一个测试,看看这个名字是否在处理的异常列表中。

try:
    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception

我添加了奖金方法,可以捕捉异常与完整的回溯,这可以帮助您了解更多的错误。

Python 3

import traceback

try:
    # your code goes here
except Exception as e:
    print(e)
    traceback.print_exc()

您可以这样做来处理一般异常

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message