[Python-ideas] Improving Catching Exceptions

Paul Moore p.f.moore at gmail.com
Fri Jun 23 10:59:09 EDT 2017


On 23 June 2017 at 15:20, Sven R. Kunze <srkunze at mail.de> wrote:
> On 23.06.2017 03:02, Cameron Simpson wrote:
>
>
> How about something like this?
>
>    try:
>        val = bah[5]
>    except IndexError:
>        # handle your expected exception here
>    else:
>        foo(val)
>
>
> That is the kind of refactor to which I alluded in the paragraph above.
> Doing that a lot tends to obscure the core logic of the code, hence the
> desire for something more succinct requiring less internal code fiddling.
>
>
> And depending on how complex bha.__getitem__ is, it can raise IndexError
> unintentionally as well. So, rewriting the outer code doesn't even help
> then. :-(

At this point, it becomes unclear to me what constitutes an
"intentional" IndexError, as opposed to an "unintentional" one, at
least in any sense that can actually be implemented.

I appreciate that you want IndexError to mean "there is no 5th element
in bah". But if bah has a __getitem__ that raises IndexError for any
reason other than that, then the __getitem__ implementation has a bug.
And while it might be nice to be able to continue working properly
even when the code you're executing has bugs, I think it's a bit
optimistic to hope for :-)

On the other hand, I do see the point that insisting on finer and
finer grained exception handling ultimately ends up with unreadable
code. But it's not a problem I'd expect to see much in real life code
(where code is either not written that defensively, because either
there's context that allows the coder to make assumptions that objects
will behave reasonably sanely, or the code gets refactored to put the
exception handling in a function, or something like that).

Paul


More information about the Python-ideas mailing list