转换FormatException处理

时间:2013-01-13 16:56:59

标签: c# .net .net-4.0 exception-handling formatexception

我正在使用转换器将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,但无法找到它是否包含字符串名称。

3 个答案:

答案 0 :(得分:3)

您可以使用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;
});

答案 1 :(得分:3)

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

答案 2 :(得分:0)

以下是我将在本次比赛中使用的内容:

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)