首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >转换FormatException处理

转换FormatException处理
EN

Stack Overflow用户
提问于 2013-01-14 00:56:59
回答 3查看 5K关注 0票数 2

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

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

我想通知用户发生故障的元素。

代码语言:javascript
复制
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,但找不到它是否包含字符串名称。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-01-14 01:00:15

您可以在lambda中捕获异常:

代码语言:javascript
复制
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);
    }
}));
票数 3
EN

Stack Overflow用户

发布于 2013-01-14 00:58:10

您可以使用TryParse方法:

代码语言:javascript
复制
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;
});
票数 3
EN

Stack Overflow用户

发布于 2013-01-14 01:20:22

下面是我在这场比赛中使用的内容:

代码语言:javascript
复制
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()方法来过滤空值:

代码语言:javascript
复制
Where(u => u != null)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14305788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档