2013-08-02 2 views
0
내가 일찍 종료를 작성하는 방법을 발견하고 컬렉션의 첫 번째 요소에 액세스하려고 할 때 예외를 throw하지 않습니다

(string [] 또는 List와 같이) 비어있는 경우. 예 :방법은 예외없이 종료 (편집 : 알려진 양식로드 문제)

var emptyList = new List<string>(); 
var aha = emptyList.Where(i => i == "four"); 
var props = aha.First(); 
//anything after here in the same method does not run 

이것이 올바른지, 어떻게 컴파일러에서 유용한 기능이 될 수 있습니까?!

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     var emptyList = new List<string>(); 
     var aha = emptyList.Where(i => i == "four"); 
     var props = aha.First(); //throws exception 



     var fdsfsa = 0; 
    } 


    private void useref() { 

     var emptyList = new List<string>(); 
     var aha = emptyList.Where(i => i == "four"); 
     var props = aha.First(); //exits method, doesn't throw exception? 

     var asdf = 0; 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     useref(); 
    } 
} 

답변

3

아니, InvalidOperationException 실패합니다 :

편집 전체 윈폼 프로그램 (닷넷 4를 사용). 나는 당신이 단지 호출 코드에서 예외를 잡는 것이라고 확신한다. 왜 '운동을

Unhandled Exception: System.InvalidOperationException: Sequence contains no elements 
    at System.Linq.Enumerable.First[TSource](IEnumerable`1 source) 
    at Test.Main() 

그래서 당신의 다음 단계는 다음과 같습니다

using System.Collections.Generic; 
using System.Linq; 

class Test 
{ 
    static void Main() 
    { 
     var emptyList = new List<string>(); 
     var aha = emptyList.Where(i => i == "four"); 
     var props = aha.First(); 
    } 
} 

결과는 : 당신의 정확한 코드을 가지고 짧지 만 전체 샘플에 넣어 - 그것은 보여 매우 쉽게 예외를 보지 못해서 - 우리는 그걸 도울 수 없습니다.

+0

아 : 아니, 예외를 Form1_Load에서 호출 할 때 여전히 throw 될 것입니다. 디버거를 단계별로 실행하면 여전히 첫 번째 예외가 발생합니다. 어쩌면 FormLoad 이벤트가 예외 (ick)를 삼키지 만 예외가 확실히 발생합니다. – Alex

+1

@ 알렉스에서 호출하지 그

try { var emptyList = new List<string>(); var aha = emptyList.Where(i => i == "four"); var props = aha.First(); } catch(InvalidOperationException ex) { //ex.message } 

+0

예외가 삼키는 것 같습니다! 분명히 이것은 64 비트 플랫폼에서 알려진 문제입니다. http://stackoverflow.com/questions/1583351/silent-failures-in-c-seemingly-unhandled-exceptions-that-does-not-crash-the-pr – Alex

0

다음보십시오 :

내가 버튼을 클릭 이벤트에 코드를 삽입 할 때 사실이지만 내가하는 방법에 넣을 때를 Form1_Load