assert or throw in range members?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 5 09:05:49 PDT 2016


On Friday, August 05, 2016 15:50:50 H.Loom via Digitalmars-d-learn wrote:
> On Friday, 5 August 2016 at 10:25:42 UTC, Nordlöw 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?
>
> nothing, but examples exist in pbobos such as front() on narrow
> strings.

That's because of invalid Unicode, not because the string was empty. It
asserts that the string is non-empty. No code anywhere should ever be
calling front or back on an empty range, and it is a programming error if it
does, not a recoverable error. We obviously don't have control over what
everyone else does with their code, but Phobos does not throw an exception
in such cases - it asserts if it does anything - and it is definitely the
consensus of the main devs that you're not using the range API correctly if
code ever calls front or back on an empty range. It is a bug to do so. There
were even some recent updates to the documentation to make some of the basic
rules around the range primitives clearer, though since it was in the
documenation for std.range, it won't be up until the next release:

https://github.com/dlang/phobos/pull/4511

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list