try... except with unknown error types

Steven D'Aprano steve+comp.lang.python at
Sat Aug 20 16:14:37 EDT 2011

Paul Rubin wrote:

> Steven D'Aprano <steve+comp.lang.python at> writes:
>>> You can catch all exceptions by catching the base class Exception:
>> Except that is nearly always poor advice, because it catches too much: it
>> hides bugs in code, as well as things which should be caught.
>> You should always catch the absolute minimum you need to catch.
> But there's no way to know what that minimum is.  Python libraries throw
> all sorts of exceptions that their documentation doesn't mention.

Yes, you're absolutely correct. But it's also irrelevant. Most of those
exceptions should not be caught, even if you know what they are, because
they represent either bugs that should be fixed, or bad data which should
raise an exception. A bare except, or except Exception, is hardly ever the
right approach.

As for exceptions which should be caught, they should be dealt with on a
case-by-case basis. There's no need to identify all those obscure
exception-raising cases ahead of time. After all, unless you're writing
software for a nuclear reactor, or an aeroplane's autopilot, chances are
that *bugs don't really matter*. That is to say, if you release software
with a hidden bug, the consequences generally aren't very important.
(Depends on the nature of the software, and the bug, of course. Sometimes
bugs are important. How's your test suite?) At some point, you will get a
bug report, and then you will fix the bug. The fix may involve catching an
extra exception, or avoiding generating the exception in the first place.

Trying to predict ahead of time every possible exception that could be
raised, and deal with them correctly (as opposed to just sweeping them
under the carpet), is not only impossible but also usually unnecessary.

It took me a long time to realise that the world won't end if I write a
piece of software with a bug. Now I realise that software is never
finished, there's always going to be a next version, so trying to make it
perfect is a fool's errand. It's very liberating :)

> Java's checked exceptions are obnoxious but they do have their
> attractions.

No doubt about it, the concept is attractive, but a few Java heavyweights
now consider checked exceptions to be a mistake.

More here:


More information about the Python-list mailing list