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


当前回答

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

Python 3

import traceback

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

其他回答

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

Python 3

import traceback

try:
    # your code goes here
except Exception as e:
    print(e)
    traceback.print_exc()
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

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

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

除了一个裸露的except:子句(其他人说你不应该使用它),你可以简单地捕获Exception:

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately. 

您通常只考虑在代码的最外层这样做,例如,如果您想在终止之前处理任何其他未捕获的异常。

except Exception相对于bare except的优点是,它不会捕获一些异常,最明显的是KeyboardInterrupt和SystemExit:如果你捕获并吞下了它们,那么任何人都很难退出你的脚本。