Best Way to Handle All Exceptions

Carl Banks pavlovevidence at gmail.com
Tue Jul 14 04:30:48 EDT 2009


On Jul 13, 8:25 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Mon, 13 Jul 2009 17:49:23 -0700, Carl Banks wrote:
> > On Jul 13, 12:31 pm, Piet van Oostrum <p... at cs.uu.nl> wrote:
> >> >>>>> seldan24 <selda... 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?
>
> > He quite reasonably could want that, such as if the program is designed
> > to be run from a cron job, or in some other non-interactive way.
>
> Why is it okay for non-interactive programs to silently have incorrect
> behaviour?
>
> What's the point of a cron job that doesn't do what it is supposed to,
> because it has a bug which is silently swallowed?

Seriously, do you *ever* take more than 2 seconds to consider whether
you might be missing something obvious before following up with these
indignant knee-jerk responses?

I never said a thing about swallowing errors.  I was talking about
catching exceptions, whence you might do all kinds of things besides
swallowing (like logging).  I was pointing out there are reasons why
you might want to catch variable misspelling errors when you're
running non-interactively (like for instance, to log the error
somewhere).

Or would you rather let all unexpected exceptions print to standard
error, which is often a black hole in non-interactive sitations?


Carl Banks



More information about the Python-list mailing list