Using exceptions with Google Guava

guava exceptionutils
guava cache exception

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 couldn't do the above because of the exception. Is there any nice pattern for handling it?

Propagate the checked exception as a RuntimeException:

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

EDIT: Since the transformed list is lazily evaluated, the exception won't be thrown until you access the list elements. You can force the evaluation by copying the transformed list into a new list, like:

s = new ArrayList<>(s);

You could wrap that in a try-catch block that catches RuntimeException and handles it however you want; your original SomeException instance can be obtained by calling getCause() on the RuntimeException. Or you could just let the RuntimeException bubble up.

Introduction to Guava Throwables, In this article, we're going to take a quick look at Google Guava's we can use Guava's Throwables class to simplify dealing with exceptions. If an exception is thrown while refreshing, the old value is kept, and the exception is logged and swallowed. This logging and swallowing of exceptions is really bad in my use case, because it means that if refresh throws an exception users of the cache will continue to find the stale data in the Cache.

You can use

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

Guava Throwables.propagate, We tend to view "log and rethrow" as an antipattern: Either handle the exception, or throw. If you throw, use exception chaining. That way, the eventual handler  Overview In this tutorial, we’ll show how to use the Google Guava's Preconditionsclass. The Preconditionsclass provides a list of static methods for checking that a method or a constructor is invoked with valid parameter values. If a precondition fails, a tailored exception is thrown.

It depends on how you want to handle the exception.

  1. Stop the list transformation when an exception occurs: See @dnault's answer.
  2. Continue the list transformation and remove the element which caused exception (and log some error message). In this case, we will return null when an exception occurs, this null value will be removed from 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 null value then you should a wrapper like this one:

class Wrapper {
    public Exception exception = null;
    public String result = null;
}

The list transformation will then be:

    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;
                }
            }));

google/guava, Throwable) will use the special implementation described in its documentation. In the unlikely case that you have three or more declared checked exception  When this occurs, we want to throw an exception with a formatted message, so we have two options: Use checkArgument() or checkState() with "false" as the condition; Throw the exception and use String.format() The first option has the advantages of being shorter and providing safety in the case of a malformed format string.

Throwables (Guava: Google Core Libraries for Java 19.0 API), Java 7+: Exceptions are suppressed by adding them to the exception that will be thrown using Throwable.addSuppressed(Throwable) . Java 6: Exceptions are  Adding Google Guava to Android project – significantly slows down the build. So, is it efficient to use Guava library in Android project or this library is designed to be used only for the server-side development, and I should go with standard solutions? Any explanations will be very appreciated.

Closer (Guava: Google Core Libraries for Java 19.0 API), I am new to Guava (and relatively new to Java).. and I am trying to use the Collections2.transform() method as follows: List<Plan> listOfPlans  In this article, we've demonstrated how to use nested exceptions in our application and implemented a utility method to find the root cause exception. We've also shown how to do the same by using third-party libraries like Apache Commons Lang and Google Guava. As always, the full source code for the examples is available over on GitHub.

How to handle exceptions in Collections2.transform()?, Newly loaded values are added to the cache using Cache. Unlike get(K) , this method does not throw a checked exception, and thus loadAll(java.lang. Guava provides the Preconditions class with a series of common preconditions. The Guava library is highly optimized. It simplifies propagating and examining exceptions and errors with help of Throwables utility. Guava’s powerful API helps in dealing with ranges on Comparable types, both continuous and discrete.

Comments
  • Use Java 8... Ha. Guava doesn't like checked exceptions.
  • @BoristheSpider How does Java 8 help? The stream API doesn't seem to allow checked exceptions either.
  • What do I put outside my transform function?
  • If you're asking what kind of declaration you need on the transform method, then you don't need any at all. That's because a RuntimeException does not need to be declared to thrown. It will just be passed up the call stack until someone's interested.
  • I don't like using null as a sentinel, to be filtered out later. What happens when someMethod legitimately returns null? It's getting messy.
  • What do you think about wrapping the result?