Index is out of range - c#

I am getting the error at getProxy(), the error is index outofbounds.
Error:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information:
Index was out of range. Must be non-negative and less than the size of the collection.
Code:
static List<String> proxies = new List<String>();
private static String getProxy()
{
lock (proxies)
{
return proxies[new Random().Next(0, proxies.Count)];
}
}
It is not empty, has a proxy inside, the error is not in my loading function, it is here.
I have added a breakpoint and debugged it, proxies has the value of Count = 3 and proxies.count has the value of 3.

The answer from #Gendolkari:
If proxies contains no elements at all, then it would be trying to
access the first element of an empty list and throw this exception.
return proxies[new Random().Next(0, proxies.Count)];
==>
return proxies[new Random().Next(0, 0)];
==>
return proxies[0];
This causes an ArgumentOutOfRangeException as stated in the documentation for List(T).Item because proxies is empty.

Related

Exception Occurred

I'm constantly getting the same error.
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '0' is not valid for 'index'.
The Code is:
private void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
{
if (e.CellElement.ColumnInfo.HeaderText == "logo")
{
if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Error")
{
e.CellElement.Image = (Image)imageList1.Images[0];
e.CellElement.ToolTipText = "Error";
}
else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Warning")
{
e.CellElement.Image = imageList1.Images[1];
e.CellElement.ToolTipText = "Warning";
}
else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Message")
{
e.CellElement.Image = imageList1.Images[2];
e.CellElement.ToolTipText = "Message";
}
}
}
}
//-----------------------------------------------------------------------
MSDN says this
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
about the ArgumentOutOfRangeException. It goes on to say that
You are retrieving the member of a collection by its index number, and the index number is invalid.
This is the most common cause of an ArgumentOutOfRangeException
exception. Typically, the index number is invalid for one of three
reasons:
The collection has no members, and your code assumes that it does.
You're attempting to retrieve an item whose index is negative. This
usually occurs because you've searched a collection for the index of a
particular element and have erroneously assumed that the search is
successful.
You're attempting to retrieve an element whose index is equal to the
value of the collection's Count property.
My suspicion is that it's the first case here, i.e. imageList1 is empty. So your imageList1.Images[0] throws the exception because there is nothing there.
To determine if this is the case try imageList1.Images.Count. Given you're looking at 3 elements in your code Count must be >= 3.
From the looks of it, you don't have anything in the array. Do a check to see if the indices are actually initialized, and then go on from there.

How to get rid from exception while finding last item in the list if an integer list is empty in C#

I have an integer list as below
List<int> lstNumber = new List<int>();
lstNumber.Add(1);
lstNumber.Add(2);
int Number = lstNumber.Last();
Here we got value 2 in the integer variable Number.
If the list is empty, I get an exception when trying to find the last element.
See code sample:
List<int> lstNumber= new List<int>();
int Number=lstNumber.Last();
Here I'm getting an exception. How can I avoid this exception?
Use LastOrDefault() instead of Last() if you are not sure about whether list is empty or not. LastOrDefault() would return default(T) if you don't have element inside the collection. In your case default(int) so following code would result in Number having 0 value.
List<int> lstNumber= new List<int>();
int Number=lstNumber.LastOrDefault(); // will not throw exception even though no element is there.
You can refer to this MSDN documentation for more details.

Exception error in Visual Basic 2013

I try to run code using C# from http://dynamicnotions.blogspot.com/2008/09/training-neural-networks-using-back.html but it give an error while running and give this message
An unhandled exception of type 'System.Exception' occurred.
I have try fix the error but another error will appear. Can anybody help me find the problem occurred in this code?
public Pattern(string value, int inputSize)
{
string[] line = value.Split(',');
if (line.Length - 1 != inputSize)
throw new Exception("Input does not match network configuration"); //error occur
_inputs = new double[inputSize];
for (int i = 0; i < inputSize; i++)
{
_inputs[i] = double.Parse(line[i]);
}
_output = double.Parse(line[inputSize]);
}
The only way I see for a System.Exception to be thrown is from the lines:
if (line.Length - 1 != inputSize)
throw new Exception("Input does not match network configuration"); //error occur
This probably means that the number of columns you say you have in your CSV int inputSize does not match the number of columns actually found in value by splitting on comma characters.
string[] line = value.Split(',');
Check your CSV file to make sure it has the same number of columns that you specify.
Note too that commas in the data itself, if not properly handled, can throw this off. For example, if you have a CSV with columns FirstName and LastName, adding "John,Smith,Jr" will make it seem like there's an extra column.

Index was out of range. Must be non-negative and less than the size of the collection

I have the following method that checks if I have object in the first index and add to it if empty
private void GetRestriction(TableRow[] RistrictionsArgs)
{
var restrictionList = new List<Restriction>();
foreach (var restriction in RistrictionsArgs)
{
var Id = int.Parse(restriction.Values.ElementAt(1));
var test = restrictionList[Id - 1];
if (test == null)
{
restrictionList[Id - 1] = new Restriction()
{
SequenceID = Id.ToString(),
};
test = restrictionList[Id - 1];
}
}
}
The problem I am having is when it reaches the line var test = restriction[Id-1]; it throws 'Index was out of range. Must be non-negative and less than the size of the collection.'
What am I missing? how can check the first element is empty and then add element to it?
No items exist in restrictionList (the length is 0), so trivially restrictionList[anyIndex] is invalid and will throw the reported exception. Lists do not automatically grow on an index operation.
To check if the the collection is empty, use restrictionList.Length == 0 (or other check as appropriate to see if a particular Id is in range). Then use Add to add a new element - not another index which will also throw an exception for the same reason as above.
Showing the actual ID's and explaining the algorithm and expected result will likely lead to better answers, as the above notes say what is currently wrong, and not necessarily "how write it correctly".

ArgumentOutofRangeException

Random r = new Random();
int InvadorNumberA=r.Next(0,5);
int randomShot = r.Next(5);
List<Invaders> invadersShooting = new List<Invaders>();
Invaders invaderA=new Invaders();
var invaderByLocationX = from invadersSortByLocation in invaders
group invadersSortByLocation by invadersSortByLocation.Location.Y
into invaderGroup
orderby invaderGroup.Key
select invaderGroup;
invadersShooting = invaderByLocationX.Last().ToList();
try
{
invaderA = invadersShooting[InvadorNumberA];// constantly being thrown there. i cant catch the exception.. so i guess it is being thrown somewhere else. any idea on how i stop it from being thrown?
}
catch(ArgumentOutOfRangeException dd)
{
invaderA = invadersShooting[0];
}
stack Trace
" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\r\n at System.ThrowHelper.ThrowArgumentOutOfRangeException()\r\n at System.Collections.Generic.List`1.get_Item(Int32 index)\r\n at WindowsFormsApplication1.Game.ReturnFire() in D:\Documents and Settings\Dima\My Documents\Visual Studio 2008\Projects\SpaceInvaders\SpaceInvaders\SpaceInvadorGame\Game.cs:line 444"
Target Site
{Void ThrowArgumentOutOfRangeException(System.ExceptionArgument, System.ExceptionResource)}
More info:
{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
i got rid of the exception by simply doing this
invadersShooting = invaderByLocationX.Last().ToList();
invaderA = invadersShooting[r.Next(0,invadersShooting.Count)];
but i am still curious,,on where the exception was thrown..hmmm
Don't do this.
Exceptions should be exceptional. You have every means to prevent this exceptional scenario and you absolutely should.
invaderA = invadersShooting[InvadorNumberA];
invaderA = invadersShooting[0];
In the first case, InvadorNumberA can be anything from 0 to 4. Check and see whether the list has at least InvadorNumberA + 1 elements in it before trying to get an element from it. Do not rely upon an exception to correct your course. More than that, perhaps InvadorNumberA should actually be constrained to random.Next(0, list.Count). Why create a number from 0 to 4 when there may only be 1 or 2 elements in the list?
It could be thrown again in you catch block, as it is not guaranteed that the size of the list is at least 1 there.
If invadersShooting is the empty list you will get an exception thrown in the try handler. You will catch this exception in the catch handler. However, you then once more index into the empty list and a new exception is thrown, this time in the catch handler. That exception is not caught and you have an unhandled exception.
Simply inspect invadersShooting.Count before trying to get an element.

Categories

Resources