我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块
try:
run_code1()
except TypeError:
run_code2()
other_code()
和这个finally的用法一样:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
我遗漏了什么吗?
我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块
try:
run_code1()
except TypeError:
run_code2()
other_code()
和这个finally的用法一样:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
我遗漏了什么吗?
当前回答
正如文档中所解释的,finally子句旨在定义在所有情况下都必须执行的清理操作。
如果finally存在,则指定一个' cleanup '处理程序。的尝试 子句,包括except和else子句。如果一个 异常发生在任何子句中而不被处理,则 异常被暂时保存。finally子句被执行。如果 有一个保存的异常,它在finally结束时被重新引发 条款。
一个例子:
>>> 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'
如您所见,finally子句在任何事件中都被执行。由分隔两个字符串引发的TypeError不由except子句处理,因此在finally子句执行后重新引发。
在实际应用程序中,finally子句用于释放外部资源(例如文件或网络连接),而不管资源的使用是否成功。
其他回答
我试图运行一个代码,我想读excel表。问题是,如果有一个文件没有表命名说:SheetSum我不能移动到错误的位置!!我写的代码是:
def read_file(data_file):
# data_file = '\rr\ex.xlsx'
sheets = {}
try:
print("Reading file: "+data_file)
sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
except Exception as excpt:
print("Exception occurred", exc_info=True)
return sheets
read_file(file)
shutil.move( file, dirpath +'\\processed_files')
给出错误:
[WinError 32]进程无法访问文件,因为它正在运行 由其他进程使用
我必须添加完整的尝试,除了与finally块,并告诉最后,我需要在任何情况下关闭文件,如:
def read_file(data_file):
# data_file = '\rr\ex.xlsx'
sheets = {}
sheets_file = None
try:
print("Reading file: "+data_file)
sheets_file = open(data_file,'rb')
sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
except Exception as excpt:
print("Exception occurred", exc_info=True)
finally:
if sheets_file:
sheets_file.close()
return sheets
read_file(file)
shutil.move( file, dirpath +'\\processed_files')
否则,文件仍然保持打开是后台。
如果出现finally,则指定一个清理处理程序。的尝试 子句,包括except和else子句。如果一个 异常发生在任何子句中而不被处理,则 异常被暂时保存。finally子句被执行。如果 有一个保存的异常,它在finally结束时被重新引发 条款。如果finally子句引发另一个异常,则保存 异常被设置为新异常的上下文。
..更多的在这里
在这里你可以看到如何尝试,除了,否则,最终一起工作。实际上,由于您的代码没有'else',那么您所声称的是正确的。也就是说,你写的两个语句之间没有区别。但是如果在某个地方使用了'else',那么'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子句都会执行。希望这能有所帮助。
try块只有一个强制子句:try语句。 except、else和finally子句是可选的,基于用户的首选项。
最后: 在Python离开try语句之前,它将在任何条件下运行finally块中的代码,即使它正在结束程序。例如,如果Python在except或else块中运行代码时遇到错误,finally块仍将在停止程序之前执行。
运行这些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的早期阶段。