If I do not specify any try and except block in python, will finally work in the program?
or I can use finally only with a try block.
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_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.
No, finally
is only used with 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. The finally
block is executed immediately after the try
or except
block, not delayed until the end of the program. See the official docs for a more thorough explanation.
finally
is useful if you need to clean up some resources before continuing. 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:
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
.
Finally, in your example, you might as well write:
if condition:
print('something')
else:
print('something else')
print('I will always run')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.