When you pass a callback in some form to another function, you often have to fullfil some interface to be able to pass such callback. That callback interface will often restrict you in what type of exceptions you can throw.
The most natural way for me would be that the called function would automatically rethrow (or ignore) the exceptions thrown by the callback. I.e. that it automatically inherits the list of exceptions it can throw from the callback. I.e. that the list of exceptions it can throw is generic.
Is something like possible already? If so, why isn't it used by Javas library yet?
If it is not possible yet, why not? It wouldn't have been complicated to include that in the language. And it would have made some things more clean (see above).
One example:
I just stumbled upon that Comparator.compare cannot throw an exception (see here for a related question) and Collections.sort (or other functions which use Comparator) also does not.
It would make much more sense to me if the exceptions which Comparator.compare can throw would be generic and Collections.sort would throw just the same. This would solve my problem here in a much more natural and clean way.
I don't see any sensible reason why ordering objects should throw an exception. I'd just return -1 if ordering is "unspecified" so that it lands in top.
I think throwing exception by a comparator breaks the single responsibility principle, the only job of a compare() method is to take two values and return a comparison result, while validness of objects should be checked earlier in a caller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With