How to avoid throwing an exceptions for a built-in function?

k-five via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 12 02:56:02 PDT 2017


On Friday, 12 May 2017 at 09:03:39 UTC, Jonathan M Davis wrote:
> 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

-----------------------------------------------------------------

Thank you for mentioning it. Since I had seen D-conference 2016 
in YouTube and it talked about isNumeric in std.traits, then I 
used std.traits. and does not worked as I wanted.

But std.string: isNumeric, worked.

string str = "string";
int index = str.isNumeric ? to!int( str ) : 0;
writeln( "index: ", index ); // 0 and without throwing any 
exceptions


More information about the Digitalmars-d-learn mailing list