Best Way to Handle All Exceptions

Piet van Oostrum piet at cs.uu.nl
Mon Jul 13 15:31:28 EDT 2009


>>>>> seldan24 <seldan24 at gmail.com> (s) wrote:

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

>s> The first example:

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

I think you should restrict yourself to those exceptions that are
related to ftp. Do you want to catch an exception like a misspelling in
one of the variables?

from ftplib import FTP, all_errors

try:
    ftp = FTP(ftp_host)
    ftp.login(ftp_user, ftp_pass)
except all_errors, err:
    print err

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list