when i get value from array/deque, i prefer the EAFP way. it is also possible in nim, but the IndexError has been deprecated, and IndexDefect is designed to be uncatchable. i found this issue, but could not found any particular reason; i know "look before you leap" way to get thing done, and i do it in my little gist.
so i really wonder why IndexError had been deprecated, especially in my opinion IndexError is similar to KeyError.
i asked this question in IM channel, but i did not get good answer before the question has been flushed away.
unfortunately, ElegantBeef's reply did not really convince me.
it's good to know the use of -d:danger and --checks:off with this scenario.
i tried compile a snippet with --checks:off, the output surprised me: deque.popLast() always returns 0; does that make sense? there is no document describes this behavior.
proc test_deque =
var x = [1].toDeque
echo "1: ", x.popLast
try:
echo "2: ", x.popLast
echo "3: ", x.popLast
echo "4: ", x.popLast
except IndexError:
echo "catched IndexError"
when isMainModule:
test_deque()
in the end, i think that behavior is a good reason to keep away from EAFP in nim.
My view is that exceptions are for exceptional code, not for simple logical errors.
even Araq will break this rule, see
IndexError was always a Defect - it merely changed name so as to highlight that it's not catchable (and never has been).
The choice between Defect and Error is, like you're noticing, quite arbitrary - there's no line that one can draw between them, rather it depends on the mood of the developer at the time of writing and sometimes the surrounding code. It is also quite subjective what you consider "exceptional" and not, so that's not that much of a useful distinction, except (haha) in extreme cases.
when i get value from array/deque, i prefer the EAFP way.
BTW simple benchmarks in the past show that raising exceptions is slower than checking for key.
> My view is that exceptions are for exceptional code, not for simple logical errors.
even Araq will break this rule, see
Correct, exceptions are control flow so I use them for control flow.
The choice between Defect and Error is, like you're noticing, quite arbitrary - there's no line that one can draw between them, rather it depends on the mood of the developer at the time of writing and sometimes the surrounding code.
Actually, the design principle is "IndexDefect is for arrays/seqs and for seq-like containers" (which a Deque is).
And yes, this is "inconsistent" with Hash tables that raise KeyError instead. Hash tables are not used for algorithms like a[x..y] = b[x..y] * c[x..y]. Different use cases produce different programming patterns which produce different takes on the error handling philosophy.