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

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.

try:
    insert(connection, data)
except:
    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.

Leave a Comment