How to handle exceptions properly in a pythonic way?

Ian Kelly ian.g.kelly at gmail.com
Mon Nov 2 15:58:39 EST 2015


On Mon, Nov 2, 2015 at 12:24 PM,  <zljubisic at gmail.com> wrote:
> I have read some articles that returning None is not a good approach, so I am confused.
>
> How to handle exceptions properly in a pythonic way?

I'm having a hard time understanding what question you're asking. You
have a lot of discussion about where to handle exceptions, but the
examples that you show are of logging the the exception and re-raising
it, which is a good practice but distinct from handling the exception.

Then you seem to be asking about the practice of returning None as an
alternative to propagating the exception, but the example you show
only returns None in a case where no exception was raised in the first
place.

None is arguably reasonable to return when it makes sense as a
non-exceptional value in the context. For example, if you're looking
up a policy that may or may not exist, then your get_policy function
might return None to indicate no value. If get_policy fails because of
an RPC timeout however, then it needs to raise an exception rather
than possibly incorrectly returning "no policy".

In comparison, if you're returning something that should always have a
value, then you should never return None. In such a case, None would
indicate that something went wrong, but it lacks any information about
*what* went wrong. An exception, on the other hand, is ideal for
carrying that sort of information. Returning None in such a scenario
is also risky in that the caller may not be expecting None and may try
to treat it as a normal value. In some cases this may even appear to
work until something breaks in a completely different part of the
code.

In the example given, the case where None is returned is clearly an
exceptional case (non-success) even though no exception was raised by
requests.get. You should raise an exception there instead of returning
None to allow the caller better control over the situation.



More information about the Python-list mailing list