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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 10 14:50:38 PDT 2017


On 05/10/2017 05:40 AM, k-five wrote:
 > I have a line of code that uses "to" function in std.conv for a purpose
 > like:
 >
 > int index = to!int( user_apply[ 4 ] ); // string to int
 >
 > When the user_apply[ 4 ] has value, there is no problem; but when it is
 > empty: ""
 > it throws an ConvException exception and I want to avoid this exception.
 >
 > currently I have to use a dummy catch:
 > try{
 >     index = to!int( user_apply[ 4 ] );
 > } catch( ConvException conv_error ){
 >     // nothing
 > }

Are you really fine with 'index' being left with its previous value? If 
so, you can write a function like the following:

void setMaybe(To, From)(ref To var, From from) {
     import std.conv : to, ConvException;
     try {
         var = to!To(from);
     } catch( ConvException conv_error ) {
     }
}

unittest {
     int index = 41;
     index.setMaybe("42");
     assert(index == 42);
     index.setMaybe("forty three");
     assert(index == 42);
     index.setMaybe("");
     assert(index == 42);
}

void main() {
}

If you want the variable to be set to a default value (perhaps .init), 
then here is an idea:

void setMaybe(To, From)(ref To var, From from, To def = To.init) {
     import std.conv : to, ConvException;
     try {
         var = to!To(from);
     } catch( ConvException conv_error ) {
         var = def;
     }
}

unittest {
     int index = 41;
     index.setMaybe("42");
     assert(index == 42);

     index.setMaybe("forty three");
     assert(index == 0);

     index.setMaybe(7);
     index.setMaybe("", 8);
     assert(index == 8);
}

void main() {
}

Ali



More information about the Digitalmars-d-learn mailing list