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.
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.