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.
Related
I sometimes run into situations where, if a line of code throws an exception, I don't care what the exception is or why it was thrown; I just need to take a generic action and move on. For example:
try
{
// Throws IndexOutOfRangeException when DB field
// is null in the current record
Template = record.GetString(MYSQL_IDX_TEMPLATE);
}
catch
{
Template = FIELD_UNAVAILABLE;
}
I was wondering if there's a short-hand way to set a value based on a generic try/catch?
I'm thinking of something similar to ternary syntax:
string blah = (index >= ubound ? "No more records" : "records exist");
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.
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.
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".
I encountered this exception while setting the SetKeyName method of ImageCollection of ImageList.
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
i have used this "imageList1.ImageStream" in my Main Form too, and it works fine there. I am stuck here and i do not know what actually this issue is, how it raised and how can i solve this.
Any suggestions and comments will be much appreciated. Thank you!!
Try this:
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia;
for (int i = 0; i < this.imageList1.Images.Count; i++)
this.imageList1.Images.SetKeyName(i, "");
Most likely this line :
this.imageList1.Images.SetKeyName(1, "");
Is causing your exception. Of course it could also be the first line with Index 0. Basically the exception is saying that code failed while trying to access the array at a given index. The reason being that the array doesn't have an item at that index.
For example in your case the code assumes that there are 2 items in the array. One at index 0 and one at index 1. If the array has only one item the second line will fail and throw the exception.
All you have to do is make sure you have an item at a given index before you try to perform any operations on it.
Something like :
if(this.imageList1.Images.Count >= 2)
{
this.imageList1.Images.SetKeyName(1, "");
}