Devarg Devarg - 3 months ago 9
C# Question

ArgumentOutOfRangeException loops when not caught

I'm writing a simple method to identify extra elements from one array on other's. After adding a throw statement with ArgumentOutOfRangeException in "Difference", seems to make the program loop forever. The program calls "Difference" with an invalid use case that throws the exception which is not caught in Main. This exception is subsequently re-trown(?), and never escapes the method and jumps sort of inside itself.

My question is...Why this program (instead of halting or letting the exception bubble up) keep looping forever in the 'throw' line, I mean, if I do catch the exception problem goes away, but for the sake of understanding what is going on on with this behaviour is that I'm writing this.

Sample code:

static void Main(string[] args)
{
int[] a = {1, 2, 3, 4}, b = {1, 2, 3, 4, 5, 6};

var diff = Difference(b, a);

foreach (var extraElement in diff)
{
Console.WriteLine(extraElement);
}

Console.ReadLine();
}

static IEnumerable<int> Difference(int[] a, int[] b)
{
if (b.Length - a.Length <= 0)
throw new ArgumentOutOfRangeException();
var extras = new int[b.Length-a.Length];
var idx = 0;
for (var i = 0; i < b.Length && idx != extras.Length; i++)
{
if (a.All(x => x != b[i])) {
extras[idx] = b[i];
idx++;
}
}

return extras;
}


Thanks in advance!

Answer

The program does not stuck at the throw statement, it is the behavior of Visual Studio to keep debugger there. If you run this program without debugging i.e. ctrl + F5 or create an exe of this console app, the program will stop running. It is not in infinite loop.