For the purpose of improving performance, do not write code with exceptions despite the normal flow.
When creating the API, there is a device to prevent the exception from being used in the normal flow. To prevent the following code from being generated, you can either prepare a hasNext method or prepare a method that returns an empty Optional or null depending on the state. The latter should be chosen if it may be accessed in parallel. The latter is better in terms of performance. The former is superior in terms of readability and ease of error detection.
// Do not use this hideous code for iteration over a collection!
try {
Iterator<Foo> i = collection.iterator();
while(true) {
Foo foo = i.next();
...
}
} catch (NoSuchElementException e) {
Recommended Posts