0

I noticed a method I wrote exits early and doesn't throw any exception when trying to access the first element in a collection (like string[] or List) if it is empty. E.g.

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

Is this correct, how can that be a useful feature in the compiler?! (using .Net 4)

Edit full winforms program:

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();
    }
}
Alex
  • 297
  • 3
  • 13

2 Answers2

3

No, that will fail with an InvalidOperationException. I'm sure you're just catching the exception in the calling code. It's very easy to show - just take your exact code and put it into a short but complete sample:

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();
    }
}

Result:

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

So your next step is to work out why you're not seeing the exception - and we can't help with that.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Ah that's true when I put the code in a button click event, but not when I put it in a method that is called from Form1_Load – Alex Aug 02 '13 at 23:03
  • 1
    @Alex: No, the exception is still going to be thrown when called from `Form1_Load` - I suspect that if you step through in a debugger, you'll still get a first-chance exception. Maybe the FormLoad event swallows exceptions (ick) but the exception is definitely thrown. – Jon Skeet Aug 02 '13 at 23:08
  • It seems exceptions are being swallowed! Apparently this is a known issue on 64bit platforms http://stackoverflow.com/questions/1583351/silent-failures-in-c-seemingly-unhandled-exceptions-that-does-not-crash-the-pr – Alex Aug 02 '13 at 23:28
0

Try the following:

try {
    var emptyList = new List<string>();
    var aha = emptyList.Where(i => i == "four"); 
    var props = aha.First();
} catch(InvalidOperationException ex) {
    //ex.message
}
Rubens
  • 14,478
  • 11
  • 63
  • 92
RobDev
  • 45
  • 1
  • 9