Alex Rivera | Logout

exceptions + signaling end-of-iterator: why is it bad in Java and normal in Python?

Asked 2011-10-17T21:10:47.180
12

I'm really confused: The standard approach in Java is to throw exceptions only in "abnormal" conditions and not to use them to signal end-of-iterator.

examples: Effective Java, item 57 ("Use exceptions only for exceptional conditions") and JavaSpecialists newsletter 162:

Flow control

We should never cause an exception that is otherwise preventable. I have seen code where instead of checking bounds, it is assumed that the data will be correct and then RuntimeExceptions are caught:

Here is an example of bad code (please don't code like this):

public class Antipattern1 {
   public static void main(String[] args) {
     try {
       int i = 0;
       while (true) {
         System.out.println(args[i++]);
       }
     } catch (ArrayIndexOutOfBoundsException e) {
       // we are done
    }
  }
}

whereas it is standard to use this idiom in Python, e.g. StopIteration:

exception StopIteration

Raised by an iterator‘s next() method to signal that there are no further values. This is derived from Exception rather than StandardError, since this is not considered an error in its normal application.

Why is it bad for Java but good for Python?

Edit
Report

2 Answers

0

StopIteration exists in Python for simple iteration over any sequence.

Using an exception to implement this was a design choice, and it really isn't that inconsistent with Java's exception mentality. An iterator's next() method being called when there are no more elements is an exceptional condition, and catching that exception behind the scenes in a for loop is a pretty simple way to implement "take items until there aren't any left".

answered 2011-10-17T21:28:12.513
0

There is no right or wrong answer to this. Exception handling is a neutral control flow construct, and the best use of it depends on context and style.

In this case, both Java and Python do the same thing, for the same reasons: java.util.Iterator's next() uses NoSuchElementException to signal end-of-iterator. This is simply good style, in both languages: the alternative of using a special sentinel return value is is much worse, for various reasons.

As a rule of thumb, you should consider the use of exceptions whenever you write a function that wants to signal more than one kind of control flow return. This includes abnormal error conditions, but good use of exception signalling is certainly not limited to that.

answered 2011-10-17T22:02:54.510

Your Answer