It depends on how you want to handle the exception.
- Stop list conversion when an exception occurs. See @ dnault answer.
Continue the list conversion and delete the element that caused the exception (and register some error message). In this case, we will return null when an exception occurs, this null value will be removed from the final list:
List<String> s = Lists.newArrayList( Iterables.filter( Iterables.transform(l, new Function<Integer, String>() { @Override public String apply(Integer i) { try { return someMethod(i); } catch (SomeException e) { e.printStackTrace(); return null; } } }), Predicates.notNull()))`
EDIT If someMethod can return a null value, then you should use a shell like this:
class Wrapper { public Exception exception = null; public String result = null; }
The list conversion will be as follows:
List<Wrapper> wrappers = Lists.newArrayList( Iterables.filter( Iterables.transform(l, new Function<Integer, Wrapper>() { @Override public Wrapper apply(Integer i) { Wrapper wrapper = new Wrapper(); try { wrapper.result = someMethod(i); } catch (SomeException e) { wrapper.exception = e; } return wrapper; } }), new Predicate<Wrapper>() { @Override public boolean apply(Wrapper wrapper) { return wrapper.exception == null; } }));
Fabien fleureau
source share