C
Chris Dunaway
VB.Net: I have create a custom collection to hold instances of my
custom class. The collection has an Item property which is set as the
default property.
I can use code such as this to retrieve an item by index or key:
Dim MyInst As MyCustomClass = MyColl("key")
My question is how should the situation of the key (or index) not
present in the list be handled?
Right now, if "key" was not in the collection, the collection would
throw an exception. To deal with that I would have to code like this:
Dim MyInst As MyCustomClass
Try
MyInst = MyColl("key")
'Process instance here
Catch ex As KeyNotFoundException
'Do something here like display a message, or whatever
End Try
But I am wondering if it would be better to not throw an exception but
to simply return Nothing if the key is not found. Then the code would
be like this:
Dim MyInst As MyCustomClass
MyInst = MyColl("key")
If MyInst Is Nothing Then
'Log error, display message, or whatever
Else
'Process instance here
End If
The cost of the exception in the first method would be high the first
time, but not afterwards, whereas the second method is more defensive.
Or would it be better to do something like this:
If MyColl.ContainsKey("key") Then
Dim MyInst As MyCustomClass = MyColl("key")
'Process instance here
Else
'Display message that key not found here
End If
What, if any, is the "standard" or best practice for such things?
Thanks for any opinions.
Chris
custom class. The collection has an Item property which is set as the
default property.
I can use code such as this to retrieve an item by index or key:
Dim MyInst As MyCustomClass = MyColl("key")
My question is how should the situation of the key (or index) not
present in the list be handled?
Right now, if "key" was not in the collection, the collection would
throw an exception. To deal with that I would have to code like this:
Dim MyInst As MyCustomClass
Try
MyInst = MyColl("key")
'Process instance here
Catch ex As KeyNotFoundException
'Do something here like display a message, or whatever
End Try
But I am wondering if it would be better to not throw an exception but
to simply return Nothing if the key is not found. Then the code would
be like this:
Dim MyInst As MyCustomClass
MyInst = MyColl("key")
If MyInst Is Nothing Then
'Log error, display message, or whatever
Else
'Process instance here
End If
The cost of the exception in the first method would be high the first
time, but not afterwards, whereas the second method is more defensive.
Or would it be better to do something like this:
If MyColl.ContainsKey("key") Then
Dim MyInst As MyCustomClass = MyColl("key")
'Process instance here
Else
'Display message that key not found here
End If
What, if any, is the "standard" or best practice for such things?
Thanks for any opinions.
Chris