Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 729
Dmitry Makovetskiyd Avatar asked Dec 17 '22 15:12

Dmitry Makovetskiyd


1 Answers

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?

like image 140
Anthony Pegram Avatar answered Jan 03 '23 18:01

Anthony Pegram