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

"in System.ThrowHelper.ThrowArgumentOutOfRangeException (argument ExceptionArgument, resource ExceptionResource) \ r \ n in System.ThrowHelper.ThrowArgumentOutOfRangeException () \ r \ n in System.Collections.Generic.List`1.get_Item (index n32) in WindowsFormsApplication1.Game.ReturnFire () in D: \ Documents and Settings \ Dima \ My Documents \ Visual Studio 2008 \ Projects \ SpaceInvaders \ SpaceInvaders \ SpaceInvadorGame \ Game.cs: line 444 "

Destination site

{Void ThrowArgumentOutOfRangeException (System.ExceptionArgument, System.ExceptionResource)}

Additional Information:

 {"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"} 

{"The index was out of range. Must be non-negative and smaller than the size of the collection. \ R \ nParameter: index"}

I got rid of the exception by just doing it

  invadersShooting = invaderByLocationX.Last().ToList(); invaderA = invadersShooting[r.Next(0,invadersShooting.Count)]; 

but I'm still wondering where the exception was thrown..hmmm

+4
source share
3 answers

Do not do this.

Exceptions must be exceptional. You have every opportunity to prevent this exceptional scenario, and you absolutely must.

 invaderA = invadersShooting[InvadorNumberA]; invaderA = invadersShooting[0]; 

In the first case, InvadorNumberA can be anything from 0 to 4. Check and check whether it contains at least InvadorNumberA + 1 elements before trying to get an element from it. Do not rely on an exception to correct your course. Moreover, perhaps InvadorNumberA should be limited to random.Next(0, list.Count) . Why create a number from 0 to 4 if the list can only have 1 or 2 elements?

+8
source

It can be flushed back to your catch block, as it is not guaranteed that the list size is at least 1.

+2
source

If invadersShooting is an empty list, you will get an exception thrown in the try handler. You will catch this exception in the catch handler. However, you then index again into an empty list and throw a new exception, this time in the catch handler. This exception was not detected, and you have an unhandled exception.

Just check invadersShooting.Count before trying to get the item.

+1
source

All Articles