19

I keep writing specific exception throwers in the case the Optional is absent.

For instance:

Optional<?> optional = ...;
if (!optional.isPresent()) {
  throw new MyException();
}
Object result = optional.get();

I find this code not very fluent, especially the use of the bang (!). I'd rather like writing something like:

Optional<?> optional = ...;
Object result = optional.orThrow(MyException.class);

Is there such a shortcut in Guava that I haven't found yet?

10
  • 6
    General question. If the thing you are checking is Optional, isn't it against the concept of "optional" to have a method like "Optional.orThrow"? Dec 16, 2011 at 13:23
  • 4
    Totally agree. If isAbsent (added in release 11) is a valid condition, it should not result in an exception. The point of Optional is that absent is a valid not exceptional case. If absent is an exceptional case, your method should just return the object and throw and exception in the absent case.
    – John B
    Dec 16, 2011 at 13:57
  • 2
    @black panda: then why can I give a default value with the or() method? It's a kind of allowing a default behavior to happen, why not another? @ John B: One of the use case is a rather generic XML attribute extractor: that attribute may or may not be present, so the method returns an Optional. Then the caller may want to enforce the presence of the value (by throwing an exception), or get the value if any, or even retrieve a default value. The extractor method just doesn't know what the caller wants to do with the value, so it must return a Optional. Why would this use case be invalid? Dec 16, 2011 at 17:28
  • 2
    Plus, you are answering with the only thing I strongly disagree with Guava: the "use exactly as we intend in our limited set of use-cases or just leave" approach. This approach is the only downside I see in Guava - a big one, but still, the only one. I love all the rest. I would have hoped not to find the same "no"-wall over here. By the way, release 11 doesn't include isAbsent() (see issue 734 of Guava) Dec 16, 2011 at 17:53
  • 3
    @ogregoire: it is common and expected behavior that if something is optional then a default value is acceptable. That's a natural extension of something being optional. "You don't specify it? Oh well, it's optional anyway, I'll use the default value." Not "This is optional. You didn't provide it? Then I'll throw an exception because it's mandatory that it be there." Dec 16, 2011 at 18:10

7 Answers 7

21

Speaking as a Guava developer, let me try to unpack the logic here. Responding both to the original question, and the comment thread directly on the question:

It is absolutely the case that we try to force Guava users to respect our standards of good programming habits. (Our standards are strongly influenced by e.g. Effective Java.)

That said, I agree that there are perfectly good use cases for the behavior you're referring to in this particular question: "if absent, throw an exception." Perhaps you're implementing a class that can be accessed both ways -- one method with an Optional return value, and one method that assumes that the value will always be present, throwing an exception otherwise. The Deque interface, for instance, provides special-valued and exception-throwing versions of peek, poll, and offer.

All that said, to the best of my understanding, the True Guava Way to do this is...

if (value.isPresent()) {
  return value.get();
} else {
  throw new MyException();
}

The "orThrow" method you propose requires reflection (!!), doesn't let you customize the exception with a useful message, etc. The "normal way" is perfectly readable and more efficient.

Sometimes Guava doesn't provide explicit support for things because for those use cases, we think it's best done just the "normal way." I think this is the case here.

3
  • 4
    Well, an orThrow() method doesn't specially require reflection: one can think about delegating the instanciation of the Exception to a Supplier or a Function. Anyways, the main point is that the "True Guava Way to do this" is repeated roughly 50 times with roughly 10 different exceptions, and only with new code produced since Guava 10! We don't want to duplicate that kind of code again and again. We've created several a helper methods (1 per Exception constructor + extras) and that's enough for us. I just wanted to know if an alternative existed, which doesn't. I won't open a ticket. Dec 17, 2011 at 21:05
  • A Supplier or Function would require the use of icky anonymous classes, and still more code than is required in the straightforward approach. If you have that much repetition it might be appropriate, although I'd think that the most effective helper methods would be one helper for each exception type, which seems to be what you've done. Dec 18, 2011 at 12:08
  • Given that Java's Optional has been around for a while and that Guava recommends using Java's Optional whenever possible, I removed the check from your answer to put it to mine which speaks about Java's Optional capabilities. I hope you don't mind. Aug 26, 2020 at 15:17
17

It is worth nothing that Java 8's Optional has an orElseThrow(Supplier) method that allows the requested behavior.

It is used like this:

Optional<Object> reference = Optional.empty()
reference.orElseThrow(MyOwnException::new); // Throws a new MyOwnException

Furthermore, a method in Java 10 was added, orElseThrow(), which throws a NoSuchElementException if no value is present.

Optional<Object> reference = Optional.empty();
reference.orElseThrow(); // Throws a new NoSuchElementException
13

Here's another way to do it without additions to Guava:

Object result = optional.or(new Supplier() {
    public Object get() {
        throw new MyException();
    }
});

MyException has to be unchecked, but this does allow you to pass arguments to its constructor. And of course if you're doing it a lot you can store the Supplier somewhere and use it each place you need it.

Object result = optional.or(SomethingIsMissing.INSTANCE);
2

I don't think this would belong to the library. I find it very rare to find a library that receives an instance of an exception to be throw in case something doesn't go as expected, especially because in many cases an exception must have a message indicating what went wrong.

That being said, you can create your own Optional class that does what you need. Or you can create your own OptionalHelper class where you have a method that does what you want:

public class OptionalHelper {
   public <T> T valueOrThrow(final Optional<T> optional) throws MyException {
      if (optional.isPresent()) {
          return optional.get();
      } else {
          throw new MyException();
      }
   }
}

EDIT:

Supposing you have a custom class that receives a parameter/ field name that you need to check, you could have a better approach similar to what Preconditions does:

public class OptionalHelper {
   public <T> T valueOrFail(final Optional<T> optional, final String fieldName) throws OptionalNotPresentError {
      if (optional.isPresent()) {
          return optional.get();
      } else {
          throw new OptionalNotPresentError(fieldName);
      }
   }
}
7
  • If you pass your own exception class, you will have to instantiate it with Class.newInstance() before throwing it. Dec 16, 2011 at 13:25
  • How would you declare this .newInstance'd exception in the throws clause? You'd have to have an general Exception subclass that you know about that contains the Exception you want to throw, right? It feels messy to me. Dec 16, 2011 at 13:36
  • It is a messy approach for sure. This is why they don't have it in the library and this is why I didn't include it in my example (only added it as a comment). Answering your question, you could get away with declaring it if you extend your exception class from RuntimeException (and not from Exception). Dec 16, 2011 at 13:45
  • It would be better to have a pre-defined exception class and pass a message/ enum value/ something else correlated with the situation being checked, and then throw that exception if the wanted object is absent from the Optional class. Dec 16, 2011 at 13:47
  • 1
    @ogregoire I don't think it has and I don't think such method belongs in the API. Dec 16, 2011 at 18:40
1

This works for me (no reflection, just type inference):

public class ExceptionSupplier<T, E extends RuntimeException> implements Supplier<T> {

    private final E exception;

    private ExceptionSupplier(E exception) {
        this.exception = exception;
    }

    public static <T, E extends RuntimeException> ExceptionSupplier<T, E> throwA(E exception) {
        return new ExceptionSupplier<T, E>(exception);
    }    

    public static <T, E extends RuntimeException> ExceptionSupplier<T, E> throwA(@SuppressWarnings("UnusedParameters") Class<T> class_, E exception) {
        return new ExceptionSupplier<T, E>(exception);
    }

    @Override
    public T get() {
        throw exception;
    }
}

Usage:

Something something = optionalSomething.or(throwA(Something.class, new SomeException()));

This probably can be extended even further, but for my use cases it's sufficient and easy to understand.

0

See official issue here

Decision: NO - too expensive, not a common pattern, can just use !isPresent(), throw

Since optional.orThrow(new Exception()) is not good for performance, I prefer static import, which is similar with@timk 's answer.

Result result = optional.or(throwException());

Equal to

Result result = optional.or(SomeSupplier.throwException());

Static method

public static Supplier<Result> throwException() {
    return new Supplier<Result>() {
        @Override
        public Result get() {
            throw new RuntimeException();
        }

    };
}

===========

The stack trace looks like

Exception ... RuntimeException
at SomeSupplier$1.get(SomeSupplier.java:line where throw RuntimeException)
at SomeSupplier$1.get(SomeSupplier.java:1)
at com.google.common.base.Absent.or(Absent.java:60)
at line where call optional.or(throwException());
4
  • What does the stack trace of this look like? How does it go in tracking down an issue when you see this in a log?
    – Ray
    Jan 12, 2016 at 8:27
  • 1
    @Ray I think it is a pattern that throw a specific exception then somewhere will handle it. Further more, the log can be understood.
    – Anderson
    Jan 12, 2016 at 8:55
  • Thanks for adding. Wasn't sure how the anonymous class gets involved in the stack trace, and I think it's relevant to the discussion
    – Ray
    Jan 12, 2016 at 12:33
  • @Ray My pleasure. Note "$1" in "SomeSupplier$1", that's the anonymous class defined in SomeSupplier.
    – Anderson
    Jan 13, 2016 at 2:40
0

A little late to the party, but here's an elegant of doing this in Guava:

Optional<?> optional = ...;
Object result = optional.or(supplyError(MyException::new));

Using the following helper method:

public static Supplier supplyError(Supplier<Error> errorSupplier) {
    return () -> { throw errorSupplier.get(); };
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.