Best Way to Handle All Exceptions

seldan24 seldan24 at
Mon Jul 13 15:26:19 CEST 2009


I'm fairly new at Python so hopefully this question won't be too
awful.  I am writing some code that will FTP to a host, and want to
catch any exception that may occur, take that and print it out
(eventually put it into a log file and perform some alerting action).
I've figured out two different ways to do this, and am wondering which
is the best (i.e. cleanest, 'right' way to proceed).  I'm also trying
to understand exactly what occurs for each one.

The first example:

from ftplib import FTP
    ftp = FTP(ftp_host)
    ftp.login(ftp_user, ftp_pass)
except Exception, err:
    print err

This works fine.  I read through the documentation, and my
understanding is that there is a built-in exceptions module in python,
that is automatically available in a built-in namespace.  Within that
module is an 'Exception' class which would contain whatever exception
is thrown.  So, I'm passing that to the except, along with err to hold
the value and then print it out.

The second example:

from ftplib import FTP
import sys
    ftp = FTP(ftp_host)
    ftp.login(ftp_user, ftp_pass)
    print sys.exc_info()

Here I, for the most part, get the same thing.  I'm not passing
anything to except and just printing out the exception using a method
defined in the sys module.

So, I'm new to Python... I've made it this far and am happy, but want
to make sure I'm coding correctly from the start.  Which method is the
better/cleaner/more standard way to continue?  Thanks for any help.

More information about the Python-list mailing list