LINQ 쿼리를 사용하여 클래스에 대한 입력 문자열을 구문 분석하고 있습니다. 구문 분석 오류를 처리하기 위해 try/catch 블록에서 쿼리를 래핑했습니다. 문제는 예외가 발생할 것으로 예상되는 지점에서 catch되지 않으며 결과 개체 (parsedList
)에 액세스 할 때 프로그램 흐름 만 중지한다는 것입니다. LINQ의 작동 방식이나 예외 작동 방식에 대해 잘못 이해 한 적이 있습니까?LINQ 쿼리의 예외가 예상되는 위치에서 catch되지 않았습니다.
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?");
}
}
}
지연된 실행. –
예를 들면 다음과 같습니다. https://blogs.msdn.microsoft.com/charlie/2007/12/10/linq-and-deferred-execution/ – Evk