Search code examples
c#.net.net-4.0exceptionformatexception

Conversion FormatException handling


I am using a Converter to convert a List<string> into a List<UInt32>

It does well, but when one of the array elements is not convertable, ToUint32 throw FormatException.

I would like to inform the user about the failed element.

try
{
    List<UInt32> MyList = SomeStringList.ConvertAll(new Converter<string, UInt32>(element => Convert.ToUInt32(element)));
}

catch (FormatException ex)
{
      //Want to display some message here regarding element.
}

I am catching the FormatException but can't find if it contains the string name.


Solution

  • You can catch exception inside the lambda:

    List<UInt32> MyList = SomeStringList.ConvertAll(new Converter<string, UInt32>(element =>
    {
        try
        {
            return Convert.ToUInt32(element);
        }
        catch (FormatException ex)
        {
           // here you have access to element
           return default(uint);
        }
    }));