nearbyatom
nearbyatom

Reputation: 37

try except not running except part

I have a short code that ftps a small file into a server.

session = ftplib.FTP("192.168.0.164", "admin", "admin")
file = open("path/test.txt", "rb")
try:
    session.storbinary("STOR application/test.txt", file)
except:
    print("failed")
else:
    print("success!")
file.close()

In the above piece I changed the IP address to so it would fail (there is no 192.168.0.164 device) and it doesn't print failed like it's supposed to. In the terminal I get a "connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" error.

if I mistype the path, I also don't get a failed print on the terminal.

If I type in the correct IP the success part does work.

Am I using the try/except wrong?

UPDATE:

Current code looks like this:

file = open("path/test.txt", "rb")
try:
    session = ftplib.FTP("192.168.0.161", "admin", "admin")
    session.storbinary("STOR application/test.txt", file)
except:
     print("Unable to reach host")
else:
    print("success!")
    session.quit()
finally:
    print ("DONE!!")
    file.close()

I figure the ftplib.all_errors will catch all errors (host unreachable, and file not found). It seems to catch the unable to reach host errors, but no file not found errors.

Upvotes: 0

Views: 113

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40888

Am I using the try/except wrong?

Your syntax is correct, but Python is not actually reaching the try block at all.

When you call session = ftplib.FTP(host, ...) where host is unreachable, the code will stop in its tracks there. That's because FTP.__init__() greedily calls self.connect(). This will in turn call socket.create_connection(), which will not succeed for an unreachable host.

So, you'd need to modify to:

with open("path/test.txt", "rb") as file:
    try:
        session = ftplib.FTP("192.168.0.164", "admin", "admin")
        session.storbinary("STOR application/test.txt", file)
    except Exception as e:
        print("failed")
        print(e)
    else:
        print("success!")
    finally:
        session.quit()

Upvotes: 3

Related Questions