How to catch error messages in ftplib?

Chris Angelico rosuav at gmail.com
Tue Nov 19 05:54:41 EST 2013


On Tue, Nov 19, 2013 at 9:18 PM, JL <lightaiyee at gmail.com> wrote:
> I have the following code;
>
>     try:
>         session = FTP(ftp_server_ip,ftp_user,ftp_password)
>         file = open(filename,'rb') # file to send
>         session.storbinary('STOR ' +  filename, file) # send the file
>     except Exception, errObj:
>         print Exception
>         print errObj
>     file.close() # close file and FTP
>     session.quit()
>
> I deliberately placed an invalid ip address for the ftp_server_ip to see whether error messages can be caught. However, no exception was thrown. Can someone more experienced point to me what did I do wrong?
>

My first suggestion would be to get rid of the try/except block - it's
not really helping you. Just let the exception be displayed. When I
try that, I get a variety of different errors, depending on what sort
of "invalid IP address" was used - if it's malformed
("192.168.1.2.3"), I get a DNS failure, if it's a computer that
doesn't exist but ought to be on my LAN ("192.168.0.2"), I get a
timeout, and if it's one that exists but doesn't have an FTP server
running ("192.168.0.3"), I get a connection refusal. Exactly what I'd
expect to see. Removing the try/except will show what's happening.

ChrisA



More information about the Python-list mailing list