June 28th, 2005, 02:33 PM
Exception Handling Basics
With the help of Grim I've gotten my little ftp script to work:
Now after reading some of the documentation on exception handling I'm wondering what the advantage is to define the exception. For instance:
from ftplib import FTP
def upload(username, password, filename, server='www.defaultftpserver.org'):
# Chop off the path so we are left
# with only the file name
file = os.path.basename(filename)
# Start the connection to the server
ftp = FTP(server)
print "Server down? I can't connect."
# Login to the server
print "Username or password is wrong dude."
# Try and upload the file
ftp.storbinary('STOR ' + file, open(filename))
print 'File %s uploaded successfully!' %file
print "Error somewhere!"
# Close the connection
Is the only value to defining the exception(e.g. ValueError) the ability to customize the action taken? Also, how do you know what type of error may occur? I'm sure this comes with experience but is there a list of some sort?
x = int(raw_input("Please enter a number: "))
print "Oops! That was no valid number. Try again..."
Finally, as I said, I'm trying to learn exception handling so I'm welcome to comments on the ftp script in terms of the error handling. Did I do it right?
Thanks in advance.
I'll learn this stuff someday.
June 28th, 2005, 06:55 PM
Try looking at dive into python at www.diveintopython.org, the exception handling section in this book is very good. Also it's free.
June 28th, 2005, 07:34 PM
Here is the list of Python 2.3 built in exceptions:
You can also create your own exceptions if these don't fit your needs.
A number of the socket exceptions are fatal to your code so in those situations there is no point running more code within the upload function (e.g. when the connection fails). Either return a failure code or raise your own exception. Conversly if the function succeeds how about a result code or no exception.
In this situation exceptions can make your code tidier because you dont have to test return values - you only manage the failures.
ftplib is one module that really uses exceptions as I'm sure your finding out. The exceptions it raises are suggested in the module iteself and detailed in the socket module docs.