在Python中处理多个异常

时间:2016-03-17 09:17:26

标签: python exception

我希望以这样的方式处理不同的异常,以便对subprocess.CalledProcessError的任何异常进行额外的特定处理。像这样:

try:
    check_output(shlex.split(rsync_cmd))
except CalledProcessException as e:
    # do some stuff
    # do common exception handling
except Exception as e:
    # do the same common handling

我不想复制代码,所以目前我最终得到了这段代码:

try:
    check_output(shlex.split(rsync_cmd))
except Exception as e:
    if isinstance(e, CalledProcessError) and e.returncode == 24:
        # do some stuff
    # do common handling

为一个例外运行特定代码以同时运行所有异常的公共代码的最佳做法是什么?

4 个答案:

答案 0 :(得分:1)

您不仅可以针对类检查错误,还可以检查类的元组。在每个分支中,您可以检查特定属性。

    try:
           n=0/0
    except (IOError, ImportError) as e:
         print(1)
    except (NameError) as e:
         print(2)

    Traceback (most recent call last):
    File "<input>", line 2, in <module>
         n=0/0
    ZeroDivisionError: division by zero

答案 1 :(得分:1)

在例外中使用继承。

class GeneralException(Exception)
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class SpecificException(GeneralException)
    def __init__(self, value):
        self.value = value
        super(SpecificException, self).__init__()
    def __str__(self):
        super(SpecificException, self).__str__()
        return repr(self.value)

基本逻辑是,您触发SpecificException并且所有super调用GeneralException来执行相关操作

答案 2 :(得分:1)

可以使用嵌套的try:...except块。我不认为这是一个令人满意的解决方案,但这是一个简单的例子。

for i in (1, 0, 'z'):
    try:
        try:
            print(i, end=' ')
            x = 1 / i
            print(x)
        except TypeError as e:
            print(e)
            raise
        except ZeroDivisionError as e:
            print(e)
            raise
    except (TypeError, ZeroDivisionError) as e:
        print('Common stuff', e)

<强>输出

1 1.0
0 float division
Common stuff float division
z unsupported operand type(s) for /: 'int' and 'str'
Common stuff unsupported operand type(s) for /: 'int' and 'str'

使用from __future__ import print_function, division

在Python 2.6.6上测试

答案 3 :(得分:0)

创建一个处理常见操作的函数。那是什么功能。

def common_exception_handling(e):
    # do stuff with e
    return  # possibly something

# ...

try:
    check_output(shlex.split(rsync_cmd))
except CalledProcessException as e:
    # do some stuff
    common_exception_handling(e)
except Exception as e:
    common_exception_handling(e)