How to avoid throwing an exceptions for a built-in function?
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 12 02:03:39 PDT 2017
On Friday, May 12, 2017 08:32:03 k-five via Digitalmars-d-learn wrote:
> On Thursday, 11 May 2017 at 19:59:55 UTC, Jordan Wilson wrote:
> > On Thursday, 11 May 2017 at 18:07:47 UTC, H. S. Teoh wrote:
> >> On Thu, May 11, 2017 at 05:55:03PM +0000, k-five via
> >>
> >> Digitalmars-d-learn wrote:
> >>> On Thursday, 11 May 2017 at 17:18:37 UTC, crimaniak wrote:
> >>> > On Wednesday, 10 May 2017 at 12:40:41 UTC, k-five wrote:
> >>> ---------------------------------------------------------
> >
> > This reason is why I sometimes use isNumeric if I have heaps of
> > strings I need to convert, to reduce exceptions. So something
> > like:
> > int index = (str.isNumeric) ? to!int(str).ifThrown(0) : 0;
> >
> > Jordan
>
> --------------------------------------------------------------
> Interesting! I was worried about performance and for that I did
> not want to use try-catch.
> So (isNumberic) is a good solution.
> http://dlang.org/phobos/std_traits.html#isNumeric
That's the wrong isNumeric. Unfortunately, both std.string and std.traits
have an isNumeric. std.traits.isNumeric is an eponymous template that tests
whether a type is an integral or floating point type, whereas
std.string.isNumeric is a templated function which tests whether a string
(or other range of characters) represents an integer or floating point
literal. So, std.traits.isNumeric won't work at all for what you want, and
std.string.isNumeric will sort of do what you want - the main caveat being
that it will also accept floating point values, whereas to!int will not.
So, if you have
auto i = str.isNumeric ? to!int(str).ifThrown(0) : 0;
then it will work but will still throw (and then be caught by ifThrown) if
str is a floating point value. Alternatively, you could check something like
auto i = str.all!isDigit ? to!int(str).ifThrown(0) : 0;
(where all is in std.algorithm and isDigit is in std.ascii), and that
_almost_ wouldn't need ifThrown, letting you do
auto i = str.all!isDigit ? to!int(str) : 0;
except that str could be an integral value that wouldn't fit in an int, in
which case to!int would throw. But std.string.isNumeric will work so long as
you're willing to have have an exception be thrown and caught if the string
is a floating point literal.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list