【问题标题】:Why use else in try/except construct in Python?为什么在 Python 的 try/except 构造中使用 else?
【发布时间】:2013-08-25 14:31:16
【问题描述】:

我正在学习 Python,但偶然发现了一个我无法理解的概念:try 构造中的可选 else 块。

根据the documentation

try ... except 语句有一个可选的 else 子句,当 现在,必须遵循所有 except 子句。它对以下代码很有用 如果 try 子句没有引发异常,则必须执行。

我感到困惑的是为什么在 try 构造中具有 如果 try 子句没有引发异常则必须执行的代码 - 为什么不简单地让它跟随 try/except at相同的缩进级别?我认为这将简化异常处理的选项。或者另一种询问方式是 else 块中的代码会做什么,如果它只是遵循 try 语句,独立于它,则不会这样做。也许我错过了什么,请赐教。

这个问题有点类似于this one,但我在那儿找不到我要找的东西。

【问题讨论】:

    标签: python exception-handling try-catch


    【解决方案1】:

    一个用例是阻止用户定义一个标志变量来检查是否引发了任何异常(就像我们在for-else循环中所做的那样)。

    一个简单的例子:

    lis = range(100)
    ind = 50
    try:
        lis[ind]
    except:
        pass
    else:
        #Run this statement only if the exception was not raised
        print "The index was okay:",ind 
    
    ind = 101
    
    try:
        lis[ind]
    except:
        pass
    print "The index was okay:",ind  # this gets executes regardless of the exception
    
    # This one is similar to the first example, but a `flag` variable
    # is required to check whether the exception was raised or not.
    
    ind = 10
    try:
        print lis[ind]
        flag = True
    except:
        pass
    
    if flag:
        print "The index was okay:",ind
    

    输出:

    The index was okay: 50
    The index was okay: 101
    The index was okay: 10
    

    【讨论】:

      【解决方案2】:

      else 块只有在try 中的代码没有引发异常时才会执行;如果您将代码放在else 块之外,那么无论是否有异常都会发生。此外,它发生在finally 之前,这通常很重要。

      当您有一个简短的设置或验证部分可能会出错时,这通常很有用,然后是一个您使用您设置的资源的块,您不想在其中隐藏错误。您不能将代码放在try 中,因为当您希望它们传播时,错误可能会转到except 子句。你不能把它放在构造之外,因为那里的资源肯定不可用,要么是因为安装失败,要么是因为finally 把所有东西都撕掉了。因此,您有一个 else 块。

      【讨论】:

      • 啊,好吧……说得通。那么为什么不把它放在 try 部分的末尾呢?是因为该代码本身可能引发异常,并且您想限制异常来源的范围吗?
      • 是的。在其他语言中,通常的做法是将其放在 try 中,尤其是在没有 except 块的情况下,但在 Python 中,我们有 else,所以我们使用它。
      • 它还允许您从 try 中返回并让返回行抛出异常,或者不:D
      猜你喜欢
      • 2013-01-13
      • 2020-08-19
      • 2019-09-28
      • 2012-11-06
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      相关资源
      最近更新 更多