Using Exclusions with Google Guava

What is the best pattern for using Google Guava with methods that should throw exceptions?

Let's say I have:

public Sting someMethod(Integer i) throws SomeException; 

And I want to do:

 List<String> s=Lists.transform(is,new Function<String, Integer>() { public String apply(Integer i) { return someMethod(i); } }); 

I could not do this due to an exception. Is there a good template to handle it?

+9
java guava exception
source share
3 answers

Distribute the checked exception as a RuntimeException:

 try { return someMethod(i); } catch (SomeException e) { throw Throwables.propagate(e, RuntimeException.class); } 

EDIT: Since the converted list is lazily evaluated, an exception will not be thrown until you access the list items. You can force the evaluation by copying the converted list to a new list, for example:

 s = new ArrayList<>(s); 

You can wrap this in a try-catch block that catches a RuntimeException and handles it the way you want; You can get your original instance of SomeException by calling getCause () on a RuntimeException. Or you can just allow a bubble of RuntimeException.

+8
source share

You can use

 public interface FunctionWithException<T, R, E extends Exception> { public R apply(T t) throws E; } 
0
source share

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; } })); 
-one
source share

All Articles