Cursors and Exception Handling

Exceptions are not generally used to change the flow of control of a program under normal circumstances. An example of using exceptions under normal circumstances is a function that iterates through a collection, and exits from the iteration by checking for the exception that is thrown when an invalid cursor is used to access elements. When the iteration is complete, the cursor will no longer be valid, and this exception will be thrown. This is not a good programming practice. A function should explicitly test for the cursor being valid. To make this possible, a function must efficiently test this condition (isValid, for the cursor example).

There are situations where the test for a condition can be done more efficiently in combination with performing the actual function. In such cases, it is appropriate, for performance reasons, to make the situation regular (that is, not exceptional) and return the condition as a IBoolean result.

Consider a function that first tests whether an element exists with a given key, and then accesses it if it exits:

if (c.containsElementWithKey (key)) {
    // ...
    myElement = c.elementWithKey (key); // inefficient
    // ...
}
else {
    // ...
}

This solution is inefficient because the element is located twice, once to determine if it is in the collection and once to access it. Consider the following example:

try {
    // ...
    myElement = c.elementWithKey (key); // bad: exception expected
    // ...
}
catch (INotContainsKeyException) {
    // ...
}

This solution is undesirable because an exception is used to change the flow of control of the program. The correct solution is to obtain a cursor together with the containment test, and then to use the cursor for a fast element access:

if (c.locateElementWithKey (key, cursor)) {
    // ...
    myElement = c.elementAt (cursor); // most efficient
    // ...
}
else {
    //...
}


Introduction to the Collection Classes
Collection Characteristics
Overview of Iteration
Iteration with Cursors


Adding an Element to a Collection
Removing an Element from a Collection
Using Cursors to Locate and Access Elements
Using allElementsDo and Applicators to Iterate Over a Collection
Instantiating the Collection Classes
Troubleshooting Problems while Using the Collection Class Library