欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

对Python中内置异常层次结构详解

程序员文章站 2023-03-01 20:09:45
如下所示: baseexception +-- systemexit +-- keyboardinterrupt +-- generatorexit...

如下所示:

baseexception
 +-- systemexit
 +-- keyboardinterrupt
 +-- generatorexit
 +-- exception
  +-- stopiteration
  +-- standarderror
  | +-- buffererror
  | +-- arithmeticerror
  | | +-- floatingpointerror
  | | +-- overflowerror
  | | +-- zerodivisionerror
  | +-- assertionerror
  | +-- attributeerror
  | +-- environmenterror
  | | +-- ioerror
  | | +-- oserror
  | |   +-- windowserror (windows)
  | |   +-- vmserror (vms)
  | +-- eoferror
  | +-- importerror
  | +-- lookuperror
  | | +-- indexerror
  | | +-- keyerror
  | +-- memoryerror
  | +-- nameerror
  | | +-- unboundlocalerror
  | +-- referenceerror
  | +-- runtimeerror
  | | +-- notimplementederror
  | +-- syntaxerror
  | | +-- indentationerror
  | |   +-- taberror
  | +-- systemerror
  | +-- typeerror
  | +-- valueerror
  |   +-- unicodeerror
  |    +-- unicodedecodeerror
  |    +-- unicodeencodeerror
  |    +-- unicodetranslateerror
  +-- warning
   +-- deprecationwarning
   +-- pendingdeprecationwarning
   +-- runtimewarning
   +-- syntaxwarning
   +-- userwarning
   +-- futurewarning
  +-- importwarning
  +-- unicodewarning
  +-- byteswarning

想要捕获所有的异常,可以直接捕获 exception 即可:

try:
 ...
except exception as e:
 ...
 log('reason:', e)  # important!

这个将会捕获除了 systemexit 、 keyboardinterrupt 和 generatorexit 之外的所有异常。 如果你还想捕获这三个异常,将 exception 改成 baseexception 即可。

以上这篇对python中内置异常层次结构详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。