April 8th, 2005, 04:19 PM
-
Exception Handling
I'm new to Python, well versed in PHP and a bit of Perl.
I've written a simple backup utility that FTPs from one server to another. I'd like to implement exception handling on the FTP should someting go wrong.
This is basically what I have so far:
Code:
try:
ftp = FTP(ftp_host, ftp_user, ftp_pass)
ftp.storbinary('STOR ' + filename, pointer)
ftp.close()
except:
I'd like to use 'all_errors' documented here.html but I don't know how! Will I have to create a handler for each other exception?
April 8th, 2005, 07:50 PM
-
Code:
import ftplib
try:
ftp = ftplib.FTP('ftp.cwi.nl') # change to invalid address to test
# user anonymous, passwd anonymous@
ftp.login()
ftp.retrlines('LIST') # change from LIST to invalid command to test
except ftplib.all_errors:
print "an error occured" #error message for any error.
here you go. make the changes to the right to test it out
Comments on this post
April 8th, 2005, 10:08 PM
-
Why use except ftplib.all_errors: when just plain old except is doing the same thing? Or can except ftplib.all_errors print out specific errors?
April 8th, 2005, 11:36 PM
-
Originally Posted by †Yegg†
Why use except ftplib.all_errors: when just plain old except is doing the same thing? Or can except ftplib.all_errors print out specific errors?
A bare except does NOT do the same thing, as it will catch errors which it shouldn't (which is why, except in rare cases such top-level error handling/logging, you should not use them). For instance:
Code:
try:
abc = 1
abc = do_something_with(acb)
except:
abc = 4
will always make abc 4. it would be much better if NameError were raised at this point. Bare excepts lead to subtle hard to track errors.
--OH.
Comments on this post
April 11th, 2005, 03:30 PM
-
I wanted to email myself the error when/if it happened, so this is what I ended up with:
Code:
try:
ftp.connect(ftp_host)
ftp.login(ftp_user, ftp_pass)
ftp.storbinary("STOR " + filename, pointer)
ftp.close()
except Exception, e:
err_msg = "Headers and stuff here"
for arg in e.args:
err_msg = err_msg + str(arg) + "\n"
from smtplib import SMTP
mFrom = 'alert@*.com'
mTo = myemail@***.com
mailer = SMTP('mail.***.com')
mailer.sendmail(mFrom, mTo, err_msg)
April 11th, 2005, 10:59 PM
-
Originally Posted by IceNine
I wanted to email myself the error when/if it happened, so this is what I ended up with:
Code:
err_msg = "Headers and stuff here"
for arg in e.args:
err_msg = err_msg + str(arg) + "\n"
That code won't work properly unless there's only one arg in e.args. If there's only one, use string formats:
Code:
err_header = "Header text\n"
err_body = "body intro: %s\n"%(e.args[0])
err_msg = err_header + err_body
If there's more than one, use a list comp and string formats:
Code:
err_header = "Header text"
err_body = ["body intro: %s"%(arg)
for arg in e.args]
err_msg = err_header + "".join(err_body)
--OH.