Best Way to Handle All Exceptions

Diez B. Roggisch deets at nospam.web.de
Mon Jul 13 10:17:53 EDT 2009


seldan24 wrote:

> Hello,
> 
> 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
> try:
>     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
> try:
>     ftp = FTP(ftp_host)
>     ftp.login(ftp_user, ftp_pass)
> except:
>     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.

The latter is - unfortunately - the better. This comes from python allowing
all kinds of objects being thrown as exceptions, not only those extending
from a common ancestor like Exception.

You seem to have a sensible take on this, but anyway I'd like to mention
that using these kinds of catch-all code is rarely justified, as it imposes
the danger of not handling errors at all. So make sure the program spits
out a sensible error-message, and then dies. Unless it's a server-process
of course.

Diez



More information about the Python-list mailing list