在Python中,捕获“所有”异常的最佳方法是什么?在Python中捕获所有异常
except: # do stuff with sys.exc_info()[1]
except BaseException as exc:
except Exception as exc:
catch可能正在执行一个线程。
我的目的是记录可能由正常代码中抛出任何异常毫无遮拦任何特殊的Python例外,比如那些指示进程终止等
获取的句柄异常(如条款以上包含exc
)也是可取的。
在Python中,捕获“所有”异常的最佳方法是什么?在Python中捕获所有异常
except: # do stuff with sys.exc_info()[1]
except BaseException as exc:
except Exception as exc:
catch可能正在执行一个线程。
我的目的是记录可能由正常代码中抛出任何异常毫无遮拦任何特殊的Python例外,比如那些指示进程终止等
获取的句柄异常(如条款以上包含exc
)也是可取的。
如果您需要捕获所有异常和所有做同样的东西,我会建议你:
try:
#stuff
except:
# do some stuff
如果你不想掩盖“特殊”蟒蛇异常,使用异常基类
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文档的exception hierarchy应该是有用的阅读。
为了避免掩盖基本的异常,您需要“重新引发”任何您不明确希望处理的异常,例如, (改编自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
except Exception:
VS except BaseException:
:
捕捉Exception
和BaseException
之间的区别在于,根据exception hierarchy异常等SystemExit,一个KeyboardInterrupt和GeneratorExit不会被捕获当使用except Exception
时,因为它们直接从BaseException
继承。
except:
VS except BaseException:
:
这两者之间的区别主要是在蟒2(AFAIK),它使用时的老式类作为要提出的一个例外,在这种情况下,仅只有表达少除了子句将能够捕捉到例外,例如。
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"
我按照正式推荐的方法(http://docs.python.org/tutorial/errors.html#user-defined-exceptions)从'Exception'继承'NewStyleException'。 – EOL
感谢您的链接到的异常层次结构。 :) – EOL