HorseloverFat HorseloverFat - 1 year ago 51
Python Question

Should I always specify an exception type in `except` statements?

When using PyCharm IDE the use of

without an exception type triggers a reminder from the IDE that this exception clause is
Too broad

Should I be ignoring this advice? Or is it Pythonic to always specific the exception type?

Answer Source

It's almost always better to specify an explicit exception type. If you use a naked except: clause, you might end up catching exceptions other than the ones you expect to catch - this can hide bugs or make it harder to debug programs when they aren't doing what you expect.

For example, if you're inserting a row into a database, you might want to catch an exception that indicates that the row already exists, so you can do an update.

    insert(connection, data)
    update(connection, data)

If you specify a bare except:, you would also catch a socket error indicating that the database server has fallen over. It's best to only catch exceptions that you know how to handle - it's often better for the program to fail at the point of the exception than to continue but behave in weird unexpected ways.

One case where you might want to use a bare except: is at the top-level of a program you need to always be running, like a network server. But then, you need to be very careful to log the exceptions, otherwise it'll be impossible to work out what's going wrong. Basically, there should only be at most one place in a program that does this.

A corollary to all of this is that your code should never do raise Exception('some message') because it forces client code to use except: (or except Exception: which is almost as bad). You should define an exception specific to the problem you want to signal (maybe inheriting from some built-in exception subclass like ValueError or TypeError). Or you should raise a specific built-in exception. This enables users of your code to be careful in catching just the exceptions they want to handle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download