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.

Python3 also removes the find() method of strings, and leaves only the index() 
method, that is like find(), but raise ValueError when the substring is not 
found. So you are forced to use exceptions here too.

I'm shocked. That's beyond stupid. Didn't they consider ease of use? Code written like that must look like a saw blade (due to the alternating indentation of the try blocks). And as noisy.

Now I'm sure they did think something when they made it like this. What am I missing?

So far in D I have used exceptions to control flow only once, in this library 
module (original code idea by Witold Baryluk, modified):
http://www.fantascienza.net/leonardo/so/dlibs/generators.html

Bye,
bearophile

Reply via email to