noexception icon indicating copy to clipboard operation
noexception copied to clipboard

Try construct

Open aghasemi opened this issue 4 years ago • 4 comments

Hi,

Thanks for the package. I really find it useful.

Is there any plan to have a try() method similar to the Try in Scala, which handles both checked and unchecked exceptions?

It could be essentially syntactic sugar for

Exceptions.log().get(Exceptions.sneak().supplier(() -> my_throwing_lambda)).orElse(fallback)

Thanks Best

aghasemi avatar Feb 18 '21 14:02 aghasemi

Wouldn't Try-like API force callers to deal with the exception and thus defeat the purpose of noexception? At the moment, the handlers are supposed to know what to do with the exception. Scala's Try merely encapsulates the exception just like Java's Future without attempting to handle it.

Anyway, I sense that you are more interested in streamlining of checked exception use cases. Perhaps an API like this would help?

Exceptions.log().checked().get(() -> my_throwing_lambda)).orElse(fallback)

Perhaps with optional custom checked exception handler:

Exceptions.log().checked(Exceptions.sneak()).get(() -> my_throwing_lambda)).orElse(fallback)

Default checked() parameter would be Exceptions.wrap() as that's least likely to cause trouble. This would go hand-in-hand with changes that would allow applications to define their own integrated checked handlers. You could then have something like this in your app:

MyExceptions.handle().get(() -> my_throwing_lambda)).orElse(fallback)

Would this solve the problem you have in mind?

robertvazan avatar Feb 18 '21 15:02 robertvazan

Thanks. I will check the checked method.

I wasn't clear with Try. What I meant is indeed more like Try{...}.toOption: Running some expression and returning an Option/Optional based on whether it has been executed in full or failed due to an exception (checked or unchecked). Am I right?

aghasemi avatar Feb 18 '21 17:02 aghasemi

The checked() method does not exist yet :-) I was just asking for feedback about such a design.

Returning Optional is what noexception is doing now. I think you just need a more convenient way to use the API with checked exceptions.

robertvazan avatar Feb 18 '21 17:02 robertvazan

Thank you. I see that Exceptions.log().get returns an Optional and it is fantastic. What I'm asking is for Exceptions.sneak().get to also return an Optional, which it currently doesn't, as far as I know. Of course one can combine the two. But IMHO this use case is frequent enough to merit a dedicated solution.

aghasemi avatar Feb 18 '21 17:02 aghasemi