3

else如果从句中有return说明,使用从句有什么意义except

def foo():
    try:
        # Some code
    except:
        # Some code
        return
    else:
        # Some code

我问这个问题是因为 Django 文档在函数中的某个时候会这样做。vote()考虑到子句中的return指令except无论如何都会停止函数的执行,为什么他们使用else子句来隔离只有在没有引发异常时才应该执行的代码?他们本可以else完全省略该条款。

4

2 回答 2

4

如果套件中没有异常try:,则else:执行套件。换句话说,只有当存在实际异常时,才会except:到达套件并使用return语句。

在我看来,这return句话在这里是多余的;一个pass就足够了。当有额外的代码只有在没有引发异常时才应该执行,但可能引发不应被捕获的异常本身时,我会使用一个else:套件。try

您是对的,return子句except中的 a 使得对那段代码使用a有点多余。else:整个套件可以被去除凹痕并删除该else:

def foo():
    try:
        # Some code
    except:
        # Some code
        return

    # Some code
于 2013-12-14T17:32:10.943 回答
4

来自文档: The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement. http ://docs.python.org/2/tutorial/errors.html#handling-exceptions

于 2013-12-14T17:33:45.563 回答