// 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){
}
上面的代码,并不是为了处理一些exception的情况,只是因为collection没有元素的时候,next()方法会抛出异常,为了跳出这个循环。我们本可以通过hasNext()方法来判断,来规避这个额外的exception。
Iterator<Foo> i = collection.iterator();
while(i.hasNext()){
Foo foo = i.next();
...
}
总结:exceptions are, as their name implies, to be used only for exceptional conditions; a well-designed API must not force its clients to use exceptions for ordinary control flow.