Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 621
Joe Avatar asked Jul 28 '14 22:07

Joe


People also ask

What is preconditions checkArgument?

checkArgument The method checkArgument of the Preconditions class ensures the truthfulness of the parameters passed to the calling method. This method accepts a boolean condition and throws an IllegalArgumentException when the condition is false.

What is guava dependency used for?

Guava is an open-source “Collection Library” library for Java, developed by Google. It provides utilities for working with Java collections. As you dive deep into Guava you'll notice how it reduces coding errors, facilitates standard coding practices and boost productivity by making code concise and easy to read.

What is Google guava JRE?

Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more!

What is throwable Java?

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.


2 Answers

Propagate the checked exception as a RuntimeException:

try {
    return someMethod(i);
} catch (SomeException e) {
    throw new RuntimeException(e);
}

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.

like image 132
dnault Avatar answered Sep 28 '22 08:09

dnault


You can use

public interface FunctionWithException<T, R, E extends Exception> {
    public R apply(T t) throws E;
}
like image 20
sheraud Avatar answered Sep 28 '22 09:09

sheraud