简体   繁体   English

捕获Python中的所有异常

[英]Catching all exceptions in Python

In Python, what's the best way to catch "all" exceptions? 在Python中,捕获“所有”异常的最佳方法是什么?

except: # do stuff with sys.exc_info()[1]

except BaseException as exc:

except Exception as exc:

The catch may be executing in a thread. catch可能在一个线程中执行。

My aim is to log any exception that might be thrown by normal code without masking any special Python exceptions, such as those that indicate process termination etc. 我的目标是记录普通代码可能抛出的任何异常,而不屏蔽任何特殊的Python异常,例如指示进程终止等的异常。

Getting a handle to the exception (such as by the clauses above that contain exc ) is also desirable. 获取异常的句柄(例如通过包含exc上述子句)也是可取的。

  • except Exception: vs except BaseException: : except Exception: vs except BaseException: ::

    The difference between catching Exception and BaseException is that according to the exception hierarchy exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when using except Exception because they inherit directly from BaseException . 捕获ExceptionBaseException之间的区别在于,根据异常层次结构异常(如SystemExit), except Exception不会捕获KeyboardInterrupt和GeneratorExit,因为它们直接从BaseException继承。

  • except: vs except BaseException: : except: vs except BaseException: ::

    The difference between this two is mainly in python 2 (AFAIK), and it's only when using an old style class as an Exception to be raised, in this case only expression-less except clause will be able to catch the exception eg. 这两者之间的区别主要在于python 2(AFAIK),并且只有在使用旧样式类作为异常时才会被引发,在这种情况下,只有表达式的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" 

If you need to catch all exceptions and do the same stuff for all, I'll suggest you this : 如果您需要捕获所有异常并为所有人执行相同的操作,我会建议您:

try:
   #stuff
except:
   # do some stuff

If you don't want to mask "special" python exceptions, use the Exception base class 如果您不想屏蔽“特殊”python异常,请使用Exception基类

try:
   #stuff
except Exception:
   # do some stuff

for some exceptions related management, catch them explicitly : 对于一些与例外相关的管理,请明确地抓住它

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

The exception hierarchy from the python docs should be a usefull reading. python文档中的异常层次结构应该是一个有用的读物​​。

In order to avoid masking basic exceptions, you need to "re-raise" any exceptions which aren't the ones which you explicitly want to handle, eg (adapted from 8. Errors and Exceptions ): 为了避免掩盖基本异常,您需要“重新引发”任何不是您明确要处理的异常 ,例如(改编自8.错误和异常 ):

import sys

try: # 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM