We're using Vavr in our project to ease exception handling. I always make sure that a method that returns a Try
can never throw anything, like so:
public Try<Result> someSafeMethod() {
return Try.of(() -> someService.generateId())
.map(someOtherService::getValueForId)
.map(mappingService::mapToResult);
}
but some of my colleagues would implement it like this:
public Try<Result> someSafeMethod() {
String generatedId = someService.generateId(); // <- Might throw an Exception that is not caught by the Try clause
return Try.of(() -> someOtherService.getValueForId(generatedId))
.map(mappingService::mapToResult);
}
Arguing that if something is wrong with the generation of the ID that they would rather the exception is thrown instead of the returned Try
being a failure.
The documentation does not prohibit that a method returning a Try
should not throw, but it does state that:
Try is a monadic container type which represents a computation that may either result in an exception, or return a successfully computed value.
Am I being too too strict? Imagine you would use an API where all methods return a Try
, wouldn't it be bad when they still throw?