如何从sys.exc_info中获取自定义异常详细信息?

时间:2015-11-08 16:11:57

标签: python

我想将一些异常处理代码合并到一个异常子句中,但是我很难获得所需的所有异常信息,因为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

总的想法是,except子句中的代码可以放在一个任何人都可以通过捕获除外调用的函数中。我正在使用Python 2.7。

2 个答案:

答案 0 :(得分:1)

我无法重现您所说代码产生的错误。

除了考虑建议使用except:dealwithIt()是一个可怕的想法,因为它会影响异常,这里是我认为你想做的代码。

import sys

class CustomException(Exception):
    def __init__(self, custom_code):
        Exception.__init__(self)
        self.custom_code = custom_code

try:
        raise CustomException("test")

except:
        ex_value = sys.exc_info()[1]
        if isinstance(ex_value,CustomException):
                print "Caught CustomException, custom_code=" + ex_value.custom_code

答案 1 :(得分:0)

这就是你需要的。

import sys

class CustomException(Exception):
    def __init__(self, custom_code):
        Exception.__init__(self)
        self.custom_code = custom_code

try:
    raise CustomException("test")

except Exception as e:
    ex = sys.exc_info()[0]
    if ex is CustomException:
            # AttributeError: 'tuple' object has no attribute 'custom_code'
            print "Caught CustomException, custom_code=" + e.custom_code
在这种情况下,{p> ex = sys.exc_info()[0] ex将类CustomException称为异常类型,而不是异常的实例。