我想將一些異常處理代碼整合到單個異常子句中,但由於exc_info缺少信息,我無法獲取所需的所有異常信息。如何從sys.exc_info中獲取自定義的異常詳細信息?
import sys
class CustomException(Exception):
def __init__(self, custom_code):
Exception.__init__(self)
self.custom_code = custom_code
try:
raise CustomException("test")
# This is OK
# except CustomException as ex:
# print "Caught CustomException, custom_code=" + ex.custom_code
# But I want to be able to have a single except clause...
except:
ex = sys.exc_info()[0]
if ex is CustomException:
# AttributeError: 'tuple' object has no attribute 'custom_code'
print "Caught CustomException, custom_code=" + ex.custom_code
的總體思路是,除了子句中的代碼可以放在一個功能,任何人都可以通過捕捉除外只需調用。我正在使用Python 2.7。
如果您希望能夠以不同的方式處理不同的異常類型,爲什麼要使用單個'except'子句?如果你想要一個'except'塊來處理幾個類型,你可以這樣做,除了(CustomException,IOError,KeyError)如:或者你想要的任何異常類型列表 –
我希望其他人能夠擁有一個除了子句並調用我的錯誤處理程序來處理所有事情除了:dealWithIt()。 –
該對象位於'sys.exc_info()[1]'中。 – tdelaney