K.Hazell
K.Hazell

Reputation: 25

Trouble with exceptions in Python

I am learning about exceptions in python and I am having trouble with some code. the following code is:

try:
    txt = open("C:\\Users\\Draco\\OneDrive\\Documents\\textfile.txt","r")
    try:
        txt.write("This is a test. Normal service will shortly resume!")
    finally:
        print("Content written to file successfully. Have a nice day.")
        txt.close()
except IOError:
    print("Error: unable to write the file. Check permissions")

Now when I execute the code I get the following to two lines: Content written to file successfully. Have a nice day. Error: unable to write the file. Check permissions

The issues I am having is that because the error, in this case being the "r" which should be "w" I should only get the message Error: unable to write the file. Check permissions. But I am getting both error and the success messages and I am unsure why

Upvotes: 0

Views: 37

Answers (2)

TTT
TTT

Reputation: 2012

I'll break it down one by one for you.

  1. Try block opened

    try:
    
  2. File opened with read privileges.

    txt = open("C:\\Users\\Draco\\OneDrive\\Documents\\textfile.txt","r")
    
  3. Try block opened, exception occurred when you wrote since you wrote to a readonly file object.

    try:
        txt.write("This is a test. Normal service will shortly resume!")
    
  4. Since you have an inner try block, the nested finally is the first block executed.

    finally:
    
  5. Printing success even though the file write failed.

    print("Content written to file successfully. Have a nice day.")
    
  6. Closing the file, works fine

    txt.close()
    
  7. Exception handler, now the exception is handled.

    except IOError:
        print("Error: unable to write the file. Check permissions")
    

Upvotes: 1

jpp
jpp

Reputation: 164613

finally always executes:

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.

The process you are seeing:

  1. Your script will not error on txt = open(loc, 'r') because at the stage it is not writing any data.
  2. When it moves on to txt.write it errors and moves to finally, for the reason given above.
  3. Since you have met an IOError, you will also see the message defined in your except clause.

Upvotes: 0

Related Questions