Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Exception Handling in Collection - Suggestions ?

Status
Not open for further replies.

MikeCallon

Programmer
Apr 29, 2004
7
0
0
GB
Hi there,

I've created a collection class, but what's the best way of handling an exception that occurs when the user of the class requests an invalid item from the collection ?

So in the Example below, what's the best way of handling the situation where the user of this class passes an iIndex greater that the number of items in the collection ?

Code:
Default Public ReadOnly Property Item(ByVal iIndex As Integer) As ProductSpecParameter
  Get            
    Return CType(List.Item(iIndex),ProductSpecParameter)
  End Get
End Property

Any comments / suggestions would be greatly appreciated :)
 
Two ways:

1. If iIndex > List.Items.Count -1 then
Return Nothing
' throw new exception ("item not found") ' ?
Else
Return CType(List.Item(iIndex),ProductSpecParameter)
End If


2. Use Try Catch block, but no use because you are able to know the possible 'error' using a simple If/Else block.

 
TipGiver, will the exception ever be thrown?

1. If iIndex > List.Items.Count -1 then
Return Nothing
' throw new exception ("item not found") ' ?


perhaps:

1. If iIndex > List.Items.Count -1 then
' throw new exception ("item not found") ' ?
Return Nothing


Hope this helps.

[vampire][bat]
 
No, because it is under the the return, you are right! But i took care of it.. commenting that line, heh

 
Hmmm, the '-1' should be deleted ,or '>' should be '>='

:)
 
Thanks for the pointers guys....

While we're at it - what if iIndex is < 0 :)

 
If (iIndex >= 0) AND (iIndex < List.Items.Count) then
' ok!
Else
' not found
End If


or use the select case

Select Case iIndex
Case 0 To List.Items.Count - 1
' ok!
Case Else
' not found
End Select
 
Or you could just not check or catch it. As soon as your class tries to get the iItem indexed object, it should throw an index out of range exception that will be passed up to the calling method.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top