On Thursday, 11 May 2017 at 18:07:47 UTC, H. S. Teoh wrote:
On Thu, May 11, 2017 at 05:55:03PM +0000, k-five via Digitalmars-d-learn wrote:
On Thursday, 11 May 2017 at 17:18:37 UTC, crimaniak wrote:
> On Wednesday, 10 May 2017 at 12:40:41 UTC, k-five wrote:
---------------------------------------------------------
> try this: > https://dlang.org/phobos/std_exception.html#ifThrown



Worked. Thanks.

import std.stdio;
import std.conv: to;
import std.exception: ifThrown;

void main( string[] args ){

        string str = "string";
int index = to!int( str ).ifThrown( 0 ); // if an exception was thrown, it
is ignored and then return ( 0 );
        writeln( "index: ", index );  // 0
}

Keep in mind, though, that you should not do this in an inner loop if you care about performance, as throwing / catching exceptions will incur a performance hit. Outside of inner loops, though, it probably doesn't matter.


T

This reason is why I sometimes use isNumeric if I have heaps of strings I need to convert, to reduce exceptions. So something like:
int index = (str.isNumeric) ? to!int(str).ifThrown(0) : 0;

Jordan

Reply via email to