[英]will finally block work without try block in python?
If I do not specify any try and except block in python, will finally work in the program?如果我没有在 python 中指定任何 try 和 except 块,最终会在程序中工作吗?
or I can use finally only with a try block.或者我只能在 try 块中使用finally 。
if condition:
print('something')
else:
print('something else')
finally:
print('I will always run')
No, it won't work outside a try
block, because finally
is part of the try
statement, as evident from Python's grammar :不,它不会在
try
块之外工作,因为finally
是try
语句的一部分,从Python 的语法中可以看出:
try_stmt: ('try' ':' suite
((except_clause ':' suite)+
['else' ':' suite]
['finally' ':' suite] |
'finally' ':' suite))
So the finally
keyword can occur only within the try_stmt
production, which captures try
statements.所以
finally
关键字只能出现在try_stmt
产生式中,它捕获try
语句。
No, finally
is only used with try
.不,
finally
仅与try
一起使用。 Its purpose is to run some code after the try
and/or any except
block, whether or not the code in the try
block threw an exception.它的目的是在
try
和/或任何except
块之后运行一些代码,无论try
块中的代码是否抛出异常。 The finally
block is executed immediately after the try
or except
block, not delayed until the end of the program. finally
块在try
或except
块之后立即执行,不会延迟到程序结束。 See the official docs for a more thorough explanation.请参阅官方文档以获得更详尽的解释。
finally
is useful if you need to clean up some resources before continuing.如果您需要在继续之前清理一些资源,
finally
很有用。 For example:例如:
f = open('myfile.txt')
try:
f.write('blabla') # This might raise an exception, for example if the disk is full
finally:
f.close() # Close the file whether the write failed or not.
Without finally
we'd have to repeat the cleanup statement, like this:如果没有
finally
我们将不得不重复清理语句,如下所示:
f = open('myfile.txt')
try:
f.write('blabla')
except:
f.close()
raise
f.close()
In Python, it is almost always better to use a with
block instead of try
/ finally
.在 Python 中,使用
with
块而不是try
/ finally
几乎总是更好。
Finally, in your example, you might as well write:最后,在您的示例中,您不妨编写:
if condition:
print('something')
else:
print('something else')
print('I will always run')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.