在Python中,捕获“所有”异常的最佳方法是什么?
except: # do stuff with sys.exc_info()[1]
except BaseException as exc:
except Exception as exc:
catch可能正在线程中执行。
我的目标是记录普通代码可能抛出的任何异常,而不屏蔽任何特殊的Python异常,例如指示进程终止等的异常。
获取异常的句柄(例如通过上面包含exc
的子句)也是可取的。
答案 0 :(得分:33)
except Exception:
vs except BaseException:
:
捕获Exception
和BaseException
之间的区别在于,根据SystemExit等exception hierarchy异常,使用except Exception
时不会捕获KeyboardInterrupt和GeneratorExit,因为它们直接继承来自BaseException
。
except:
vs except BaseException:
:
这两者之间的区别主要在于python 2(AFAIK),并且只有在使用旧样式类作为异常时才会被引发,在这种情况下,只有expression-less except子句才能捕获异常,例如
class NewStyleException(Exception): pass
try:
raise NewStyleException
except BaseException:
print "Caught"
class OldStyleException: pass
try:
raise OldStyleException
except BaseException:
print "BaseException caught when raising OldStyleException"
except:
print "Caught"
答案 1 :(得分:22)
如果您需要捕获所有异常并为所有人做同样的事情,我会建议您:
try:
#stuff
except:
# do some stuff
如果您不想屏蔽“特殊”python异常,请使用Exception基类
try:
#stuff
except Exception:
# do some stuff
对于一些与例外相关的管理,明确地抓住它们:
try:
#stuff
except FirstExceptionBaseClassYouWantToCatch as exc:
# do some stuff
except SecondExceptionBaseClassYouWantToCatch as exc:
# do some other stuff based
except (ThirdExceptionBaseClassYouWantToCatch, FourthExceptionBaseClassYouWantToCatch) as exc:
# do some other stuff based
python docs中的exception hierarchy应该是一个有用的阅读。
答案 2 :(得分:0)
为了避免掩盖基本异常,您需要“重新引发”任何不是您明确要处理的异常,例如: (改编自8. Errors and Exceptions):
import systry: # do something that could throw an exception: except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) except ValueError: print "Could not convert data to an integer." except: # maybe log the exception (e.g. in debug mode) # re-raise the exception: raise