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?
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.
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.
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!
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.
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.
You can use
public interface FunctionWithException<T, R, E extends Exception> {
public R apply(T t) throws E;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With