0

I notice that in a lot of code I'm not interested in the Exception that is thrown in a called method. I just want to get an Optional if it succeeds, and an empty() if not.

Is there something similar to ofNullable, but then instead an ofThrowable, where I pass a function reference? Then I could do something like:

myOptionalString.flatMap(ofThrowable(Integer::parseInt))
Jeroen Kransen
  • 1,379
  • 3
  • 19
  • 45
  • not that I know of, but nobody is stopping you from creating a static method that catches an exception and returns `Optional.empty()` instead. – J Asgarov Feb 15 '22 at 07:40
  • I can, but that would be so generic that I would expect it to be in Optional itself. I was hoping there's already a common(s) library that has it. – Jeroen Kransen Feb 15 '22 at 07:42
  • 2
    It is a questionable idea, since swallowing exceptions is considered a bad practice. I totally understand your use case, I just wouldn't expect the OpenJDK community to happily provide such a method. They would tell you to use filter instead `Optional.of(yourString).filter(this::isValidNumber).map(Integer::parseInt)` – J Asgarov Feb 15 '22 at 07:47
  • 1
    @JAsgarov no need to vendor provide such method to catching exception, indeed you can simple add as many method as you want to stream api :), https://stackoverflow.com/questions/48010544/how-do-i-write-a-custom-stream-function – Lunatic Feb 15 '22 at 08:27
  • @JAsgarov I disagree that this would "swallow" the Exception. It would just convert one type ("Try") into another (Optional), something that is very common in a language like Scala. – Jeroen Kransen Feb 15 '22 at 19:24
  • @JeroenKransen provided there is only one execution flow that results in an empty Optional your point is valid. But if there is an alternative flow that also results in empty Optional as well, user wouldn't know if an exception took place and hence it was swallowed. One might argue a different type of Optional might be needed to express this situation e.g. `Optional.exception()` – J Asgarov Feb 15 '22 at 19:35

1 Answers1

0

The simplest way is to surround the ofThrowable(or generally the piece of code you trying to catch the exception) with try catch and return desired optional as return value of each block,

public class Main {
    public static void main(String[] args) {
        yourOptional.flatMap(o ->
        {
            try {
                return Optional.of(ofThrowable(Integer::parseInt, o));
            } catch (Exception e) {
                return Optional.empty();
            }
        });
    }

    public static Integer ofThrowable(Function<String, Integer> extractor, Integer value) throws Exception {
        //some logic perhaps
        throw new Exception();
    }
}

Indeed you can add whole try catch as method and add it to Stream api.

Lunatic
  • 1,519
  • 8
  • 24
  • 1
    I was not looking for something that would work, that's trivial. I was looking for something that is elegant. Having blocks of code inside a Stream obfuscates the flow and defeats its purpose imho. – Jeroen Kransen Feb 15 '22 at 19:28