How to handle exceptions properly in a pythonic way?

Chris Angelico rosuav at gmail.com
Wed Nov 4 23:51:41 EST 2015


On Thu, Nov 5, 2015 at 3:18 PM,  <zljubisic at gmail.com> wrote:
>> Which would you prefer?
>
> So if I am just checking for the ConnectionError in get_html and a new exception arises, I will have traceback to the get_html function showing that unhandled exception has happened.
> Now I have to put additional exception block for managing the new exception in the get_html function and I am covered.
>
> Is that what you wanted to say?

Yep. I would definitely recommend having get_html raise an exception
on any problem; here's the structure I'd use:

def get_html(...):
    try:
        ... actually go get the info
        return info
    except (ConnectionError, OSError, SocketError) as e:
        raise ContentNotFoundError from e

This means there are three possibilities:

1) Everything works correctly, and get_html returns something useful.

2) An exception occurs of a type that you expect - the server didn't
respond, or the OS threw back a failure, or whatever. (You'd decide
what set of exceptions this represents.) In this case, you get a
single exception that wraps that up and summarizes the problem as
"Content Not Found". The original exception is retained in the
__cause__ of the ContentNotFoundError, so no information is lost.

3) An unexpected exception occurs - your script runs out of memory, or
there's a bug in your code, or anything else. The exception will
simply bubble up, and be dealt with somewhere else.

To use this code, what you'd do is:

try:
    data = get_html(...)
except ContentNotFoundError:
    # deal with the case of not having anything to work with

Omitting the try/except is a perfectly reasonable way of working, too.
Just call get_html, and if ever it can't get a result, the exception
continues to propagate. It's easy, it's straight-forward, and it's
unambiguous - any problem you don't expect becomes an exception.

ChrisA



More information about the Python-list mailing list