【发布时间】:2016-06-14 15:23:02
【问题描述】:
我正在使用 LINQ 查询将输入字符串解析为类。我已将查询包装在 try/catch 块中以处理解析错误。问题是异常没有在我期望它发生的点被捕获,它只在访问结果对象(parsedList)的点停止程序流。我是否误解了 LINQ 的工作原理或异常的工作原理?
public class Foo
{
public decimal Price { get; set; }
public decimal VAT { get; set; }
}
public class MyClient
{
public IEnumerable<Foo> ParseStringToList(string inputString)
{
IEnumerable<Foo> parsedList = null;
try
{
string[] lines = inputString.Split(new string[] { "\n" }, StringSplitOptions.None);
// Exception should be generated here
parsedList =
from line in lines
let fields = line.Split('\t')
where fields.Length > 1
select new Foo()
{
Price = Decimal.Parse(fields[0], CultureInfo.InvariantCulture), //0.00
VAT = Decimal.Parse(fields[1], CultureInfo.InvariantCulture) //NotADecimal (EXCEPTION EXPECTED)
};
}
catch (FormatException)
{
Console.WriteLine("It's what we expected!");
}
Console.WriteLine("Huh, no error.");
return parsedList;
}
}
class Program
{
static void Main(string[] args)
{
MyClient client = new MyClient();
string inputString = "0.00\tNotADecimal\n";
IEnumerable<Foo> parsedList = client.ParseStringToList(inputString);
try
{
//Exception only generated here
Console.WriteLine(parsedList.First<Foo>().Price.ToString());
}
catch (FormatException)
{
Console.WriteLine("Why would it throw the exception here and not where it fails to parse?");
}
}
}
【问题讨论】:
-
延迟执行。
标签: c# linq exception-handling