我想将一些异常处理代码整合到单个异常子句中,但由于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