Search code examples
javaoption-type

How to easily convert Exception to Optional.empty()


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

Solution

  • The library throwing-function implements that functionality.

    In pom.xml:

        <dependency>
            <groupId>com.pivovarit</groupId>
            <artifactId>throwing-function</artifactId>
            <version>1.5.1</version>
        </dependency>
    

    To use it:

    import static com.pivovarit.function.ThrowingFunction.lifted;
    
    [...]
    
    myOptionalString.flatMap(lifted(Integer::parseInt))
    

    PS. I'm not the library author; I don't know them and they doesn't know me.