Search code examples
javaexceptioniooption-type

How can I return an optional instead of throwing an exception?


I have a method that can possibly throw an error. This exception is out of my control, as it is an IO exception, not a exception I am throwing. Instead of adding a throws statement to my method or fitting it in a try and catch block, would I be able to return an optional via this method?

Summary: I have a method to return a value T, except to get to that value, I have to add a try/catch block or throws statement to my method. Can I return an Optional of type T instead of throwing this error?


Solution

  • "Instead of adding a throws statement to my method or fitting it in a try and catch block"

    Well, those are your two options. Either you can

    • Catch the exception yourself and return an empty Optional. This is not a good idea as it hides the exception, OR
    • You can let the exception propagate.
    • I suppose a third option is to wrap the exception in an unchecked exception, but that just makes your interface murkier.

    If you really want to defer error handling to the caller and not throw, the ideal solution is to implement a composite object to return, containing both the error status and the return value if there is one.