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?
"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
Optional
. This is not a good idea as it hides the exception, ORIf 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.