Codesmell for java Optional.orElseThrow() with null supplier

Hi

Just have seen this in our code:

Optional<String> foo = Optional.ofNullable("bar");
var s = foo.orElseThrow();

There is no exception supplier defined inside the orElseThrow() invocation, according to documentation this will lead to a NullPointerException. The compiler does not complain about it.

I think this is a code smell that should be detected by sonar because this always indicates that the developer missed to declare the exception to be thrown.

Kind regards,
Michael

Hi Michael,

Thank you for your suggestion.

Just to be clear: Since the optional in your example has a value, no exception will be thrown and s will have the value “bar”. An exception would only be thrown if the optional were empty. And in that case it would be a NoSuchElementException, not a NullPointerException.

And as far as I can tell, there’s nothing wrong with that. It seems perfectly reasonable to me that someone might not want to define a custom exception (or message) to be thrown here and would be okay with a NoSuchElementException. I would not consider this a code smell.

If you feel strongly that you always want an exception to be specified with orElseThrow in your code base, you can define a custom rule for that, but I don’t think this makes sense as a general rule.

Cheers,
Sebastian

You are right, I missed the overload of orElseThrow() because I looked to the outdated java8 doc.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.