0

My code looks like this:

cIndex = (int)rand.Next(App.viewablePhrases.Count);
phrase = App.viewablePhrases[cIndex];

Infrequently it's giving me an error:

Application Specific Information:
*** Terminating app due to uncaught exception 'SIGABRT', reason: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

Xamarin Exception Stack:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  at System.Collections.Generic.List`1[T].get_Item (System.Int32 ) <0x10047bfc0 + 0x0007b> in <939d99b14d934342858948926287beba#d346c1f46aec0f7ce096300b9d7adc79>:0
  at CardsTabViewModel.Random () <0x10138a5d0 + 0x0013b> in <1a94c4e2e6ff49bab0334b2d6333fc29#d346c1f46aec0f7ce096300b9d7adc79>:0

Is there a way I could catch this exception to show more details?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 3
    Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – gunr2171 Oct 22 '19 at 13:35
  • 1
    By the way, the error message says "[The index value] Must be non-negative and less than the size of the collection." – gunr2171 Oct 22 '19 at 13:37
  • you can catch the `ArgumentOutOfRangeException` explicitly; it has an `ActualValue ` property that you can inspect to see what broke you. – Gus Oct 22 '19 at 13:37
  • 1
    Is it possible that the collection is modified elsewhere before the second line is executed? – vc 74 Oct 22 '19 at 13:42
  • Don't think this is a duplicate; the referenced duplicate seems more focused on `IndexOutOfRangeException`, and while the advice is still useful for `ArgumentOutOfRangeException`, the latter exception provides more information that can directly answer OP's question – Gus Oct 22 '19 at 13:50
  • Probably due to inappropriate multi-threaded access - either to the collection or to the random. But since we're not really shown enough code involved with either of them, difficult to say at present. – Damien_The_Unbeliever Oct 22 '19 at 13:56

2 Answers2

1

Is there a way I could catch this exception to show more details?

Just put your code in try / catch block like this:

try
{
 cIndex = (int)rand.Next(App.viewablePhrases.Count);
 phrase = App.viewablePhrases[cIndex];
}
catch(System.ArgumentOutOfRangeException e)
{
  Console.WriteLine("Exception information: {0}", e);
}
catch(Exception e)
{
  Console.WriteLine("Exception information: {0}", e);
}

Set a break point in catch block to see more information.

Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92
0

Index can be from 0 to Count-1.