assert or throw in range members?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 5 04:50:56 PDT 2016


On Friday, August 05, 2016 10:25:42 Nordlöw via Digitalmars-d-learn wrote:
> Should range members front() and back() assert() or throw() on
> emptyness?
>
> If it should assert() doesn't that lead to unsafer code in
> release mode?
>
> What's the consensus here?

It is a programming error for any range members other than empty, length, or
save to be called when a range is empty. So, it definitely should not be an
exception. Phobos asserts on such things, though if you're paranoid about
it, you can always explicitly throw an Error of some kind (e.g. RangeError).
But that will incur a performance hit in release mode, and it's perfectly
normal for checks like this to not be enabled in release mode. Testing is
supposed to catch such problems before you actually release your code.
Regardless, throwing an Exception is the wrong behavior, because it's
considered a programming error for those functions to be called when a range
is empty. Nothing should ever result in front or back being called when the
range is empty.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list