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

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

和这个finally的用法一样:

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

我遗漏了什么吗?


当前回答

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

...

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块将是多余的。

其他回答

如果你早点回来,情况就不一样了:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   # The finally block is run before the method returns
finally:
    other_code()

与此相比:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   

other_code()  # This doesn't get run if there's an exception.

其他可能导致差异的情况:

如果在except块内抛出异常。 如果在run_code1()中抛出异常,但它不是TypeError。 其他控制流语句,如continue和break语句。

完美的例子如下:

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)

运行这些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的早期阶段。

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

...

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块将是多余的。

为了让Abhijit Sahu对这个答案的评论更好看,并突出显示语法:

像这样,你可以观察到在以下情况下哪个代码块发生了什么:

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)