Best Way to Handle All Exceptions

MRAB python at mrabarnett.plus.com
Mon Jul 13 16:33:42 CEST 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.
> 
There isn't an "exceptions module"; exceptions are part of the language.

> 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()
> 
This is called a "bare exception handler". It's virtually never the
right way to do it.

> 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.

You should use the most specific exception possible because at lot of
things could raise an exception:

 >>> foo

Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
     foo
NameError: name 'foo' is not defined
 >>> try:
     foo
except Exception, e:
     print "*** Caught an exception ***"
     print e

*** Caught an exception ***
name 'foo' is not defined



More information about the Python-list mailing list