[Python-ideas] Consistent programming error handling idiom

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Apr 10 01:38:41 EDT 2016


Rian Hunter wrote:
> I want a consistent opt-in idiom with community consensus. I want a 
> clear way to express that an exception is an error and not an internal 
> bug.

There's already a convention for this. Exceptions derived
from EnvironmentError (OSError in python 3) usually
result from something the user did wrong. Anything else that
escapes lower-level exception handling is probably a bug.

So my top-level exception handlers usually look like this:

    try:
       ...
    except EnvironmentError as e:
       # Display an appropriate error message to the user
       # If it's something interactive, go back for another
       # request, otherwise exit

Anything else is left to propagate and generate a traceback.

It's not perfect, but it works well enough most of the time.
If I find a case where some non-bug exception gets raised that
doesn't derive from EnvironmentError, I fix things so that
it gets caught somewhere lower down and re-raised as an
EnvironmentError.

So the rule you seem to be after is probably "If it's likely to
be a user error, derive it from EnvironmentError, otherwise don't."

I think that's about the best that can be done, considering
that library code can't always know whether a given exception
is a user error or a bug, because it depends on what the
calling code is trying to accomplish.

For example,

    some_library.read_file("confug.ini")

will probably produce an OSError (file not found) even though
it's the programmer's fault for misspelling "config".

-- 
Greg


More information about the Python-ideas mailing list