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

k-five via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 13 02:51:40 PDT 2017


On Saturday, 13 May 2017 at 09:05:17 UTC, Jonathan M Davis wrote:

> For the most part, when parsing a string, std.conv.to's 
> approach of just parsing the string and throwing an exception 
> if/when it fails is the most efficient, because it's only going 
> to parse the string once, whereas calling a function to 
> validate the string's format and _then_ do the conversion would 
> mean parsing the string twice.It's just that if you are in a 
> situation where the string is likely not to be in the correct 
> format, then having a bunch of exceptions thrown will harm 
> performance. To best handle that, we'd need an alternate 
> conversion function that did something like return the failure 
> condition and passed the result via an out parameter or one 
> which took a default value and returned that on failure instead 
> of what was actaully parsed. So, ideally, we'd have other 
> functions in std.conv to handle such cases, but in the vast 
> majority of cases, throwing an exception on failure is going to 
> be the most efficient solution.

I did not know this.

> But obviously, to know what's actually happening with your 
> code, you're going to have to profile and benchmark it -

Can you please give a link or page or something to read about 
profile or benchmark. I have no experience with those.

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

For a such purpose I already used std::stringstream in C++, and I 
assumed may or may not D has a such family. ( to!, parse!, ... )

Not only an invalid string like "word" for to!int, makes it being 
thrown, but an empty string like: "" also makes it.

string str = "word";
int index = to!int( str ); // throws

str = "";
int index = to!int( str ); // throws, as well!

Of course throwing is useful some times, but definitely not 
ALWAYS, and it is better to have a convert function that never 
throws anything.

Although [Andrei Alexandrescu] told me that the parse! family is 
used for such a case:
> Use the "parse" family: 
> https://dlang.org/phobos/std_conv.html#parse -- Andrei
but it throws as well.


More information about the Digitalmars-d-learn mailing list