ExceptionSafeIterator implements Iterator<T> { public static <T> ExceptionSafeIterator<T> wrap(Iterator<T> iterator) { return new ExceptionSafeIterator<>(iterator); } private  ExceptionSafeIterator(final Iterator<T> iterator); static ExceptionSafeIterator<T> wrap(Iterator<T> iterator); @Override boolean hasNext(); @Override T next(); @Override void remove();  }
@Test public void testIteratorWithExceptions() { final Iterator<Integer> throwIterator = new Iterator<Integer>() { private final Integer[] numbers = { 0, 1, null, 2, null, null, 3, null, null }; private int n = 0; @Override public boolean hasNext() { return n < numbers.length; } @Override public Integer next() { if (numbers[n] == null) { n++; throw new UnsupportedOperationException(); } return numbers[n++]; } @Override public void remove() { } }; final Iterator<Integer> evens = ExceptionSafeIterator.wrap(throwIterator); assertArrayEquals(new Integer[]{0, 1, 2, 3}, Iterators.toArray(evens, Integer.class)); }