2016-06-14 3 views
1

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?"); 
     } 
    } 
} 
+1

지연된 실행. –

+0

예를 들면 다음과 같습니다. https://blogs.msdn.microsoft.com/charlie/2007/12/10/linq-and-deferred-execution/ – Evk

답변

3

강제 실행하지 않는 한 LINQ 쿼리는 실제로 필요하기 전까지 실행되지 않습니다 ("지연된 실행"). 필요한 부분 만 ("게으른 평가") 완전히 실행되지 않을 수도 있습니다. https://msdn.microsoft.com/en-gb/library/mt693152.aspx이 : https://blogs.msdn.microsoft.com/ericwhite/2006/10/04/lazy-evaluation-and-in-contrast-eager-evaluation/

당신은 LINQ 쿼리의 끝에 .ToList() 또는 .ToArray() 같은 것을 추가하여 즉시 완전한 실행을 강제 할 수

이 참조.

관련 문제