Why do we need the “finally” clause in Python?

前端 未结 14 1836
感情败类
感情败类 2020-11-28 16:58

I am not sure why we need finally in try...except...finally statements. In my opinion, this code block

try:
    run_code1()
except          


        
相关标签:
14条回答
  • 2020-11-28 18:04

    As explained in the documentation, the finally clause is intended to define clean-up actions that must be executed under all circumstances.

    If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause.

    An example:

    >>> def divide(x, y):
    ...     try:
    ...         result = x / y
    ...     except ZeroDivisionError:
    ...         print("division by zero!")
    ...     else:
    ...         print("result is", result)
    ...     finally:
    ...         print("executing finally clause")
    ...
    >>> divide(2, 1)
    result is 2.0
    executing finally clause
    >>> divide(2, 0)
    division by zero!
    executing finally clause
    >>> divide("2", "1")
    executing finally clause
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in divide
    TypeError: unsupported operand type(s) for /: 'str' and 'str'
    

    As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.

    In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

    0 讨论(0)
  • 2020-11-28 18:05

    Perfect example is as below:

    try:
        #x = Hello + 20
        x = 10 + 20 
    except:
        print 'I am in except block'
        x = 20 + 30
    else:
        print 'I am in else block'
        x += 1
    finally:
        print 'Finally x = %s' %(x)
    
    0 讨论(0)
提交回复
热议问题