[Python-ideas] Improving Catching Exceptions
Cameron Simpson
cs at zip.com.au
Thu Jun 22 21:02:56 EDT 2017
On 22Jun2017 19:47, Andy Dirnberger <dirn at dirnonline.com> wrote:
>> On Jun 22, 2017, at 7:29 PM, Cameron Simpson <cs at zip.com.au> wrote:
>> try:
>> foo(bah[5])
>> except IndexError as e:
>> ... infer that there is no bah[5] ...
>>
>> Of course, it is possible that bah[5] existed and that foo() raised an IndexError of its own. One might intend some sane handling of a missing bah[5] but instead silently conceal the IndexError from foo() by mishandling it as a missing bah[5].
>>
>> Naturally one can rearrange this code to call foo() outside that try/except, but that degree of control often leads to quite fiddly looking code with the core flow obscured by many tiny try/excepts.
[...]
>
>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.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Python-ideas
mailing list