[英]Catching all exceptions in Python
在Python中,捕獲“所有”異常的最佳方法是什么?
except: # do stuff with sys.exc_info()[1]
except BaseException as exc:
except Exception as exc:
catch可能在一個線程中執行。
我的目標是記錄普通代碼可能拋出的任何異常,而不屏蔽任何特殊的Python異常,例如指示進程終止等的異常。
獲取異常的句柄(例如通過包含exc
上述子句)也是可取的。
except Exception:
vs except BaseException:
::
捕獲Exception
和BaseException
之間的區別在於,根據異常層次結構異常(如SystemExit), except Exception
不會捕獲KeyboardInterrupt和GeneratorExit,因為它們直接從BaseException
繼承。
except:
vs except BaseException:
::
這兩者之間的區別主要在於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"
如果您需要捕獲所有異常並為所有人執行相同的操作,我會建議您:
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文檔中的異常層次結構應該是一個有用的讀物。
為了避免掩蓋基本異常,您需要“重新引發”任何不是您明確要處理的異常 ,例如(改編自8.錯誤和異常 ):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.