我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块

try:
    run_code1()
except TypeError:
    run_code2()
other_code()

和这个finally的用法一样:

try:
    run_code1()
except TypeError:
    run_code2()
finally:
    other_code()

我遗漏了什么吗?


当前回答

运行这些Python3代码来查看finally的需求:

CASE1:

count = 0
while True:
    count += 1
    if count > 3:
        break
    else:
        try:
            x = int(input("Enter your lock number here: "))

            if x == 586:
                print("Your lock has unlocked :)")

                break
            else:
                print("Try again!!")

                continue

        except:
            print("Invalid entry!!")
        finally:
            print("Your Attempts: {}".format(count))

例2:

count = 0

while True:
    count += 1
    if count > 3:
        break
    else:
        try:
            x = int(input("Enter your lock number here: "))

            if x == 586:
                print("Your lock has unlocked :)")

                break
            else:
                print("Try again!!")

                continue

        except:
            print("Invalid entry!!")

        print("Your Attempts: {}".format(count))

每次尝试以下输入:

随机整数 正确的代码是586(试试这个,你会得到你的答案) 随机字符串

**在学习Python的早期阶段。

其他回答

专业地使用delphi几年教会了我如何使用最后来保护我的清理程序。Delphi在很大程度上强制使用finally来清理try块之前创建的任何资源,以免导致内存泄漏。这也是Java、Python和Ruby的工作原理。

resource = create_resource
try:
  use resource
finally:
  resource.cleanup

不管你在try和finally之间做了什么,资源都会被清理。此外,如果执行从未到达try块,它将不会被清理。(例如create_resource本身抛出异常)它使你的代码“异常安全”。

至于为什么你需要一个finally块,并不是所有的语言都需要。在c++中,你可以自动调用析构函数,当异常展开堆栈时,析构函数会强制执行清理。我认为与尝试相比,这是朝着更干净的代码方向迈进了一步。最后的语言。

{    
  type object1;
  smart_pointer<type> object1(new type());
} // destructors are automagically called here in LIFO order so no finally required.

下面是一段代码来澄清两者的区别:

...

try: 
  a/b
  print('In try block')
  
except TypeError:
  print('In except block')
  
finally: 
  print('In finally block')

print('Outside')

A b = 0,1

输出:

In try block 
In finally block 
Outside

(没有错误,除了跳过块。)


A b = 1,0

输出:

In finally block

Traceback (most recent call last):
a/b
ZeroDivisionError: division by zero

(没有为ZeroDivisionError指定异常处理,只执行finally块。)


A, b = 0, '1'

输出:

In except block 
In finally block 
Outside

(异常被正确处理,程序没有中断。)


注意:如果你有一个except块来处理所有类型的错误,finally块将是多余的。

Finally也可以用于在运行主要工作的代码之前运行“可选”代码,而可选代码可能由于各种原因而失败。

在下面的例子中,我们不知道store_some_debug_info会抛出什么样的异常。

我们可以运行:

try:
  store_some_debug_info()
except Exception:
  pass
do_something_really_important() 

但是,大多数lint会抱怨捕捉到的异常过于模糊。此外,由于我们选择只传递错误,except块并没有真正增加值。

try:
  store_some_debug_info()
finally:
  do_something_really_important()     

上面的代码与第一个代码块具有相同的效果,但更简洁。

试着先运行这段代码,不要使用finally块,

1 / 0导致除零误差。

    try:
        1 / 0    
        print(1)
        
    except Exception as e:
        1 / 0
        print(e)
        

然后尝试运行这段代码,

    try:
        1 / 0    
        print(1)
        
    except Exception as e:
        1 / 0
        print(e)
   
    finally:
        print('finally')

对于第一种情况,你没有finally块, 因此,当在except块中发生错误时,程序执行将停止,并且在except块之后不能执行任何东西。

但对于第二种情况, 错误发生,但在程序停止之前,python先执行finally块,然后导致程序停止。 这就是为什么你要用finally来做真正重要的事情。

为了补充上面的其他答案,无论发生什么,finally子句都会执行,而else子句只在没有引发异常时执行。

例如,写入一个没有异常的文件将输出以下内容:

file = open('test.txt', 'w')

try:
    file.write("Testing.")
    print("Writing to file.")
except IOError:
    print("Could not write to file.")
else:
    print("Write successful.")
finally:
    file.close()
    print("File closed.")

输出:

Writing to file.
Write successful.
File closed.

如果存在异常,代码将输出以下内容(注意,故意使文件保持只读会导致错误。

file = open('test.txt', 'r')

try:
    file.write("Testing.")
    print("Writing to file.")
except IOError:
    print("Could not write to file.")
else:
    print("Write successful.")
finally:
    file.close()
    print("File closed.")

输出:

Could not write to file.
File closed.

我们可以看到,无论异常如何,finally子句都会执行。希望这能有所帮助。