繁体   English   中英

Try-Except-Else-finally返回in else替代?

[英]Try-Except-Else-Finally return in else alternative?

我正在开发一个可以raise多个Exceptions的函数。 我想在其except块中处理这些Exceptions ,然后使用自定义消息和回溯返回结果。 问题是finally得到保证所以我不能在else块内返回任何else

如果引发了一些Exception则此代码有效,但如果没有Exception则不起作用。 在这种情况下,我想要返回{'success':True}

所以从这段代码:

def foo():
    try:
        #some code
        return {'success':True}
    except FirstException:
        tb = traceback.format_exc()
        msg = 'There was FirstExc'
        return {'success':False,
                'tb':tb,
                'msg':msg}
    except SecondException:
        tb = traceback.format_exc()
        msg = 'There was SecondExc'
        return {'success':False,
                'tb':tb,
                'msg':msg}
    ...

我不想重复returns 我试过了:

def foo():
    try:
        pass
    except FirstException:
        tb = traceback.format_exc()
        msg = 'There was FirstExc'
    except SecondException:
        tb = traceback.format_exc()
        msg = 'There was SecondExc'
    else:
        return {'success':True}
    finally:
        return {'success':False,
                'tb':tb,
                'msg':msg}

你知道怎么做吗? 我知道我可以将return {'success':True}放入try块,删除finallyelse块并将return {'success':False,'tb':tb,'msg':msg}到每个exceptexcept但是exceptexcept还有很多,所以代码会重复多次。

还有其他选择吗?

不要使用finally块。 您只想为异常返回False ,否则返回True ; finally返回总是适用于两种情况。

您可以从套房except两个房间返回,也可以组合套房。

从两者返回会导致更多重复:

def foo():
    try:
        pass
    except FirstException:
        tb = traceback.format_exc()
        msg = 'There was FirstExc'
        return {'success':False,
                'tb':tb,
                'msg':msg}
    except SecondException:
        tb = traceback.format_exc()
        msg = 'There was SecondExc'
        return {'success':False,
                'tb':tb,
                'msg':msg}
    else:
        return {'success':True}

您可以将except套件合并为一个:

def foo():
    try:
        pass
    except (FirstException, SecondException) as e:
        tb = traceback.format_exc()
        exception_type = 'FirstExc' if isinstance(e, FirstException) else 'SecondExc'
        msg = 'There was {}'.format(exception_type)
        return {'success':False,
                'tb':tb,
                'msg':msg}
    else:
        return {'success':True}

另一种方法是建的返回值,然后根据需要添加信息:

def foo():
    result = {'success': True}
    try:
        pass
    except FirstException:
        tb = traceback.format_exc()
        msg = 'There was FirstExc'
        result = {'success': False, 'tb': tb, 'msg': msg}
    except SecondException:
        tb = traceback.format_exc()
        msg = 'There was SecondExc'
        result = {'success': False, 'tb': tb, 'msg': msg}
    finally:
        return result

然而,这与return -from-the-suite-suite选项并没有什么不同。

def foo():
    success = False
    try:
        pass
    except FirstException:
        tb = traceback.format_exc()
        msg = 'There was FirstExc'
    except SecondException:
        tb = traceback.format_exc()
        msg = 'There was SecondExc'
    else:
        success = True
    finally:
        return {'success':success,
                'tb':tb,
                'msg':msg} if not success else {'success':success}

替代方案:

def foo():
    result = {"success": False}
    try:
        pass
    except FirstException:
        result['tb'] = traceback.format_exc()
        result['msg'] = 'There was FirstExc'
    except SecondException:
        result['tb'] = traceback.format_exc()
        result['msg'] = 'There was SecondExc'
    else:
        result['success'] = True
    finally:
        return result

上面的略有变化:

def foo():
    result = {"success": False}
    try:
        pass
    except FirstException:
        result.update({'tb': traceback.format_exc(), 'msg': 'There was FirstExc'})
    except SecondException:
        result.update({'tb': traceback.format_exc(), 'msg': 'There was SecondExc'})
    else:
        result['success'] = True
    finally:
        return result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM