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


当前回答

要捕获所有可能的异常,请捕获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))

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

其他回答

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

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

我刚刚发现了在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

要捕获所有可能的异常,请捕获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))

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