On 23Jun2017 15:59, Paul Moore firstname.lastname@example.org wrote:
On 23 June 2017 at 15:20, Sven R. Kunze email@example.com wrote:
On 23.06.2017 03:02, Cameron Simpson wrote: How about something like this?
try: val = bah except IndexError:
# handle your expected exception here
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.
While I agree that in object with its own __getitem__ would look "deep", what I was actually suggesting as a possibility was a "shallow" except catch, not some magic "intentional" semantic.
A shallow catch would effectively need to mean "the exceptions uppermost
traceback frame referers to one of the program lines in the try/except suite".
Which would work well for lists and other builtin types. And might be insufficient for a duck-type with python-coded dunder methods.
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).
Sure, there are many circumstances where a succinct "shallow catch" might not be useful. But there are also plenty of circumstances where one would like just this flavour of precision.
Cheers, Cameron Simpson firstname.lastname@example.org