Best Way to Handle All Exceptions

Floris Bruynooghe floris.bruynooghe at gmail.com
Mon Jul 13 11:13:34 EDT 2009


On Jul 13, 2:26 pm, seldan24 <selda... at gmail.com> wrote:
> The first example:
>
> from ftplib import FTP
> try:
>     ftp = FTP(ftp_host)
>     ftp.login(ftp_user, ftp_pass)
> except Exception, err:
>     print err

*If* you really do want to catch *all* exceptions (as mentioned
already it is usually better to catch specific exceptions) this is the
way to do it.

To know why you should look at the class hierarchy on
http://docs.python.org/library/exceptions.html.  The reason is that
you almost never want to be catching SystemExit, KeyboardInterrupt
etc. catching them will give you trouble at some point (unless you
really know what you're doing but then I would suggest you list them
explicitly instead of using the bare except statement).

While it is true that you could raise an object that is not a subclass
from Exception it is very bad practice, you should never do that.  And
I've haven't seen an external module in the wild that does that in
years and the stdlib will always play nice.


Regards
Floris



More information about the Python-list mailing list