方法链接的异常处理

时间:2018-10-17 04:25:16

标签: python-3.x exception

class A:
    def __init__(self, data):
        self.data = data
    def first():
        # Some functionality
        # raise Exception on some condition
        return self
    def second():
       #Some functionality

a = A('test string').first().second()

在这种情况下,我希望如果first()引发错误,则链接中断并且引发该错误。目前,它只是默默地失败。

我该如何解决?

2 个答案:

答案 0 :(得分:0)

您可能要做的最好的事情是定位链中可能出现的错误的类型,然后阶梯化异常处理程序:

class A:
    def __init__(self, data):
        self.data = data
    def first(self):
        # Some functionality
        # raise Exception on some condition
        if self.data=='A':
            1/0
        return self
    def second(self):
        next(0)
        pass
       #Some functionality   

您会知道first是数字,而second是一个可能具有TypeError的可迭代函数。

所以尝试一下:

try:
    A('A').first().second() 
except ZeroDivisionError as e:
    print('Likely first:', e)   
except TypeError as e:
    print('Likely second:', e)

如果使用Likely first: division by zero,将用A('A')打印Likely second: 'int' object is not an iterator并打印A('something_else')。如果要停止执行链,则可以使用此构造。

您还可以添加raise来重新引发该错误并获得Python对何时何地的诊断:

try:
    A('B').first().second() 
except ZeroDivisionError as e:
    print('Likely first:', e)   
    raise
except TypeError as e:
    print('Likely second:', e)
    raise 

打印:

Likely second: 'int' object is not an iterator
Traceback (most recent call last):
  File "Untitled 79.py", line 19, in <module>
    A('B').first().second() 
  File "Untitled 79.py", line 14, in second
    next(0)
TypeError: 'int' object is not an iterator

或者,更好的是,在每种方法中分别使用tryexcept

class A:
    def __init__(self, data):
        self.data = data
    def first(self):
        try: 
            1/0
        except ZeroDivisionError as e:
            print('DEFINITELY first:', e)       
        return self
    def second(self):
        try: 
            next(0)
        except TypeError as e:
            print('DEFINITELY second:', e)      
        return self

>>> A('').first().second()
DEFINITELY first: division by zero
DEFINITELY second: 'int' object is not an iterator

答案 1 :(得分:0)

如果它实际失败,我认为它不会无声地失败,因为这会导致python错误。但是,您可能想要这样的东西,也许会激发您的思考。

class A:
    def __init__(self, data):
        self.data = data

    def first():
        try:
            # Some functionality
            raise ERROR_YOU WANT_RAISE:

        # raise Exception on some condition
        except ERROR_TO_CATCH_FROM_RAISE:
            # This is where you would handle the exception after its caught
            # and break your chaining possibly. Set a flag for second() 
            # for example that handles the error.

        return self

    def second():
       #Some functionality