try-except block:用于' else'如果引起异常

时间:2015-11-11 08:39:08

标签: python exception exception-handling try-except

我有这样的代码:

try:
    return make_success_result()
except FirstException:
    handle_first_exception()
    return make_error_result()
except SecondException:
    handle_second_exception()
    return make_error_result()

我想知道有没有办法实现这个目标:

try:
    # do something
except Error1:
    # do Error1 specific handling
except Error2:
    # do Error2 specific handling
else:
    # do this if there was no exception
????:
    # ALSO do this if there was ANY of the listed exceptions (e.g. some common error handling)

因此代码以下列顺序之一执行:

try > else > finally
try > except > ???? > finally
  

编辑:我的观点是????块应该在任何except块后立即执行,这意味着它是错误处理的补充,而不是替换。

5 个答案:

答案 0 :(得分:5)

在这种情况下我要做的是在你得到异常时设置一个布尔值,如下所示:

got_exception = False
try:
    # do something
except Error1:
    # do Error1 specific handling
    got_exception = True
except Error2:
    # do Error2 specific handling
    got_exception = True
else:
    # If there was no exception
finally:
    if got_exception:
        # ALSO do this if there was ANY exception (e.g. some common error handling)

这应该符合您的需求,这是IMO最简单的方法,可以将所有解决方案组合到最易于调试的最易读的代码结构中。

答案 1 :(得分:2)

你可以这样做:

try:
    # Do something
except Error1:
    # Do Error1 specific handling
except Error2:
    # Do Error2 specific handling
except Exception:
    # Handle any other exception (Generic exception handling)
else:
    # Do this if there were no exceptions
finally:
    # Execute this regardless

答案 2 :(得分:1)

你实际上可以这样做:

try:
    print 'try'
    # 1/0
    # {}[1]
    # {}.a
except AttributeError, KeyError:  # only handle these exceptions..
    try:
        raise                     # re-raise the exception so we can add a finally-clause executing iff there was an exception.
    except AttributeError:
        print 'attrerr'
        # raise ...               # any raises here will also execute 'common'
    except KeyError:
        print 'keyerror'
    finally:                      # update 0: you wanted the common code after the exceptions..
        print "common"

else:
    print 'no exception'

但它很可怕,我不建议你没有大量的评论来描述原因......

UPDATE:除了内部try-block中的有趣异常之外,您不需要捕获任何内容。代码已更新。

UPDATE2:根据OP的说明,common应该在抛出有趣的异常时执行。代码已更新。 @MatTaylor的版本绝对是要走的路; - )

答案 3 :(得分:0)

是的,python中的异常处理包括elsefinally子句。你可以这样做:

try:
    # do something
except Error1:
    # do Error1 specific handling
except Error2:
    # do Error2 specific handling
else:
    # do this if there was no exception
finally:
    # Do this in any case!

python docs提到这些块,即使它没有显示您需要的完整示例。

编辑: 我看到你没有专门要求清理一般情况。 Python文档就是这样说的:

  

try语句有另一个可选子句,用于定义必须在所有情况下执行的清理操作。

请注意,无论是否存在异常,finally都会运行。结合else块,你仍然可以做你想做的事。

答案 4 :(得分:0)

您可以捕获所有错误,并在错误处理代码中检查其类型,如下所示:

try:
    # do something
except Exception as e:
    if isinstance(e, Error1):
        # do Error1 specific handling
    elif isinstance(e, Error2):
        # do Error2 specific handling
    else:
        # do non-Error1/Error2 handling
    # ALSO do this if there was ANY exception (e.g. some common error handling)
else:
    # do this if there was no exception