How to catch the exception og the index out of bound error

Dear Programmer,

I would to know how do catch exception such as index out of bound error for arraylist in VB.net. For instance, when the index reach negative value, then it will prompt me an error message saying "Index was out of range. Must be non-negative and less than the size of the collection."

How can I solve this proble Thanks

--Maria--



Answer this question

How to catch the exception og the index out of bound error

  • Tiendq

    I'd just like to comment that this one also comes down to philosophy: if, at design time, you know there's a possibility of the array being out of bounds, I would check that the index is in bounds, and do something meaningful.

    Using error handling, although very powerful, doesn't really add anything to the situation: you still have to handle it (which, actually, is the most important: how you handle the 'error'). In this case - array bounds - it is easily checked for, without throwing an error. A database connection, for example, is not necessarily something easily checked and an error handling routine is probably appropriate.

    Catching the 'error' is only part of the job - what you do with it is actually most important.

    (I'll get off my soapbox, now - I've seen one too many 'unhandled exception' errors, and dialog boxes in distributed applications saying 'array out of bounds' - an end user does not care about your programming problems).



  • kamran khawaja

    Hi Maria!

    I don't think you really want to catch it. You have a bug. I believe you want to fix it.

    The try-catch is really good and it's the right answer to the question asked. But I don't agree with the solution set proposed within the question.

    So I'd propose a slight mod to Richards's code:

    Try
    Array(Index)=something
    Catch
    debugger.break
    End Try

    This'll set a invoke a break point in the code and you can single step around and find the error.

    IF you had anything but vbe, you could look at the call stack and tell what routines called your routine.

    Anyway, I think this method is an improvement. I hope it works for you. :)



  • AnanthK

    Thanks a lot for your help! I have fix the deg already. Thank you so much XD


  • manicm

    There's alwyas a try-catch block as well:

    Try
    Array(Index)=something
    Catch
    msgbox("Array out of bounds")
    End Try


  • Chanchito

    ... And for the record, I wasn't attempting to solve the exact problem, just suggesting a method for dealing with it ;)
  • Axel.C

    You could do an if statement.

    If index > 0 and index < array.count() Then
    'Do some stuff with the array here
    array(index) = 5
    End If

  • How to catch the exception og the index out of bound error