Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try, except, finally ?
#1
Hi all,

I've been trying to tighten up my code by adding error handling using the try command, but I can't seem to get my head around the "finally" statement. I admit I have just been using Python with pygame to make games but I can't seem to find an occassion where I need to use the "finally" statement in a "try" block. I can only presume that I don't really understand it.

Does anyone have any scenarios where its proven more convenient to include the "finally" statement block? Pray

"""
A module to try and work out the 'finally'
statement in a 'try' block.
"""

try:
    f = open("demofile.txt")
    f.write("Lorum Ipsum")
except:
    print("Something went wrong when writing to the file.")
finally:
    f.close()
PS. The above code requires the text file to be read-only.

Looking at the common example of cleaning up and not leaving a file open, I don't understand Huh why I just don't just have the close statement without the "finally" block? Was it just introduced to act as a sort of self documentation?
Reply
#2
(Apr-28-2019, 08:45 PM)microphone_head Wrote: why I just don't just have the close statement without the "finally" block?

You have an empty except statement. Generally you should be catching specific errors, like an IOError. If you got a different kind of error, the close call wouldn't execute without the finally block. Also, if you raise an error in your except block (which I do a fair amount to clarify error messages), it wouldn't execute without the finally block.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Here is an example
try:
    print('file open')
    raise PermissionError
except FileNotFoundError as exception:
    print(exception)
finally:
    print('file closed in finally')
    
print('file closed outside try/except/finally')
Error:
file open file closed in finally Traceback (most recent call last): File "C:\Users\Dave\Documents\Eclipse Workspace\Test\forum\forum_post.py", line 4, in <module> raise PermissionError PermissionError
The code is expecting to get a FileNotFoundError but there is actually a unexpected PermissionError
The file close in the finally still happens, if there was no finally the one after would not close the file.
Reply
#4
Wow Doh ! I've read a few examples but I think I finally get it Blush , thanks. That a great help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with try, except, else finally Pytho13 14 4,936 Mar-23-2021, 05:35 PM
Last Post: snippsat
  Am I a retard - else and finally blocks in a try statement RubenF85 6 2,514 Jan-12-2021, 05:56 PM
Last Post: bowlofred
  finally clause Skaperen 6 3,813 Jun-02-2019, 09:02 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020