Conversion FormatException handling

本文关键字:handling FormatException Conversion | 更新日期: 2023-09-27 17:52:56

我正在使用转换器将List<string>转换为List<UInt32>

它做得很好,但是当其中一个数组元素不可转换时,ToUint32抛出FormatException

我想通知用户失败的元素。

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.
}

我正在捕捉FormatException,但无法找到它是否包含字符串名称。

Conversion FormatException handling

可以在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);
    }
}));

您可以使用TryParse方法:

var myList = someStringList.ConvertAll(element =>
{
    uint result;
    if (!uint.TryParse(element, out result))
    {
        throw new FormatException(string.Format("Unable to parse the value {0} to an UInt32", element));
    }
    return result;
});

我将在这个比赛中使用:

List<String> input = new List<String> { "1", "2", "three", "4", "-2" };
List<UInt32?> converted = input.ConvertAll(s =>
{
    UInt32? result;
    try
    {
        result = UInt32.Parse(s);
    }
    catch
    {
        result = null;
        Console.WriteLine("Attempted conversion of '{0}' failed.", s);
    }
    return result;
});

你总是可以使用Where()方法来过滤空值:

Where(u => u != null)