Python:最终是否需要try-except子句?

Python:最终是否需要try-except子句?,python,except,finally,Python,Except,Finally,假设以下代码 try: some_code_1 except: # will it be called twice, if an error occures in finally? some_code_2 finally: some_code_3 假设在某些代码\u 3中发生异常。我是否需要在some\u code\u 3(见下文)周围添加一个try-except子句,或者将再次调用some\u code\u 2的异常,这在原则上可能会导致无限循环 这是储蓄吗 try:

假设以下代码

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    some_code_3
假设在
某些代码\u 3
中发生异常。我是否需要在
some\u code\u 3
(见下文)周围添加一个try-except子句,或者将再次调用
some\u code\u 2
的异常,这在原则上可能会导致无限循环

这是储蓄吗

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    try:
        some_code_3
    except:
        pass

python不会返回到执行流中,而是逐语句返回

当它到达
最后
时,如果在那里抛出错误,它还需要另一个句柄

请尝试一下:

try:
    print(abc) #Will raise NameError
except: 
    print("In exception")
finally:
    print(xyz) #Will raise NameError

Output: 
In exception
Traceback (most recent call last):
  File "Z:/test/test.py", line 7, in <module>
    print(xyz)
NameError: name 'xyz' is not defined
试试看:
打印(abc)#将引发名称错误
除:
打印(“例外”)
最后:
打印(xyz)#将引发名称错误
输出:
例外
回溯(最近一次呼叫最后一次):
文件“Z:/test/test.py”,第7行,在
打印(xyz)
名称错误:未定义名称“xyz”

所以不,它不会以无限循环结束

示例代码中的finally不会捕获某些代码的异常

是否需要捕获某些代码的异常取决于您的设计。

请。。你为什么不呢?