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

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 13 02:23:41 PDT 2017


On Saturday, 13 May 2017 at 08:50:20 UTC, k-five wrote:

> Way arguing when a simple code can clarify the subject? right?
> If am not clear so consider me as an stupid man, no problem at 
> all.
>
> but CAN you please solve it for me?
>
> import std.stdio:	writeln;
> import std.conv:	to;
>
> void main( string[] args ){
> 	
> 	string str = "10";
> 	int index;
> 	index = to!int( str );	// okay, no exception are thrown
> 	
> 	str = "some-words";
> 	index = to!int( str ); // problem, an exception is thrown
> 	
> }
>
> Please run this code and convert "some-words" to int by using 
> to! function without facing any exception. Thanks

Please don't take it the wrong way. It just seems that Mike was 
as confused by your questions as I was initially. But it's clear 
that's just the language barrier, nothing more. See, you said:

> Why I do not want to take care of that? Because I just need the 
> value, if the string is valid, otherwise no matter what the 
> value of string is.

...but it doesn't make sense to have an int "value" for a string 
like "some-words". *Unless* one defines a "not-a-number" 
equivalent for an int, i.e. 0 or some other value. That part was 
hard to infer from what you were saying :) It might've been 
obvious for you, but hard to understand from what you wrote.

This was what made things clear:

> I just want to silent this exception...

Mostly, the source of the confusion was the "I don't want to 
handle the exception". But in fact what you were asking was was 
there a way to somehow ignore the exception and just return some 
predefined value in case of an error. So in fact, you did want to 
handle the exception (or rather, an exceptional case), you just 
wanted to do it without inserting control flow instructions 
(try/catch) into your code. I think the latter part already got 
covered in others' replies.

Nobody was trying to insult you. With this being a multi-lingual 
and multi-cultural community, remember that understanding goes 
both ways, and we're sometimes caught right in the middle, in the 
clash of mentalities.


More information about the Digitalmars-d-learn mailing list