对Python中内置异常层次结构详解
程序员文章站
2022-06-01 16:38:06
如下所示:
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中内置异常层次结构详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。