Benchmark of try/catch

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Mar 23 08:04:50 PDT 2009


grauzone wrote:
> bearophile wrote:
>> grauzone:
>>
>>> From your site:<
>>
>> I don't own LiveJournal :-) That's just my blog, my site is elsewhere.
>>
>>
>>> Using exceptions in a string->int conversion routine is really 
>>> horrible and incredibly stupid.<
>>
>> I agree that it's not nice looking, but in Python that's the standard 
>> idiom.
>> In D I do the same thing when I want to know if a string contains an 
>> integer or float, with toInt/toFloat, how can I do it with no exceptions?
> 
> IMHO best would be something like this:
> 
> (int|Error) toInt(char[] s);
> 
> The return value would have a dynamic type of either int or Error. One 
> could do all sorts of things with it, like explicitly checking for the 
> type and read out the actual data, or implicit conversion with throwing 
> an exception if the type is not the correct one. Error can be an object 
> that contains an error message (like Exception).
> 
> Alternatively, one could introduce nullable types:
> 
> int? toInt(char[] s);
> 
> The use of nullable value type int? would be a bit similar to object 
> references in D. One can check it for null-ness, and using a null value 
> raises a special exception.
> 
> As a third way, one could simply return a tuple:
> 
> (bool, int) toInt(char[] s);
> 
> The bool value would tell if the string was successfully parsed. If it's 
> true, the second item of the tuple contains the parsed value. But this 
> is hardly better than the standard D solution, where you'd use an "out" 
> parameter to return one of the two return values.

In D as of today you can use:

Algebraic!(int, Exception) toInt(in char[] s);

or

Tuple!(int, "result", bool, "succeeded") toInt(in char[] s);

(See std.variant and std.typecons.) What Phobos does in the particular 
case of conversions is:

string s = "12a";
auto i = to!int(s); // throws
auto j = parse!int(s); // returns 12, advances s to "a"


Andrei



More information about the Digitalmars-d mailing list