Idiomatic error handling for ranges

Timoses timosesu at gmail.com
Thu Apr 5 17:32:05 UTC 2018


On Thursday, 5 April 2018 at 17:06:04 UTC, rumbu wrote:
> Is there a standard way to handle errors in a chain of range 
> transformations?
>
> Let's say I want to read some comma separated numbers from a 
> file.
>
> auto myArray = file.byLine().splitter().map!(to!int).array();
>
> Now, besides fatal errors (like I/O), let's suppose I want to 
> handle some errors in a silent way:
> - skip unicode decoding errors;
> - assume blank records with 0;
> - skip the line entirely if the conversion to int is not 
> possible;
>
> I can catch UTFException, ConvException or 
> ConvOverflowException for the entire syntax chain but there are 
> some disadvantages:
> - I don't know exactly which of the chain members thrown the 
> exception;
> - I cannot skip/handle the error and continue;
>
> The only solution I thought about is to break the nice chain 
> syntax and handle errors on each of the chain members, but I 
> wonder if there is probably another way.
>
> Thanks.

You could use predicates:

```
     string list = "3, 5, 1, , not a number, 100";

     int[] numbers = list.split(",").filter!((entry) {
         if (!isNumeric(entry.strip))
             return false;
         else // ... even more cases?
             return true;
     	})
         .map!((e) => e.strip.to!int).array;

     assert(numbers == [3, 5, 1, 100]);
```
https://run.dlang.io/gist/413282d9726dbac137bf5f35033a8eea


More information about the Digitalmars-d-learn mailing list