Jump to content
Sign in to follow this  
vivek

Code mistake in the python course in topic Python Try...Except

Recommended Posts

While learning python from w3schools, I encountered a bug in the code in the section Python Try...Except. While explaining Finally concept, there is one example given to explain the Finally block

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()   #Compilation issue. Not correct

This code is giving the below compilation issue

Traceback (most recent call last):
  File "try.py", line 8, in <module>
    f.close()
NameError: name 'f' is not defined

It is because if "demofile.txt" is not present then open will failed to open and nothing will get assigned to the f.

f variable will be none. So when it will execute the f.close() code written in the finally block,  it will through the compilation error as it is trying to close some invalid file descriptor.

Please have a look into this issue and let me know if my understanding is correct

 

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...